Reputation: 51
When the HTML is mapped through the examples array, there is an index given. But when I click the button to addToCart, the elements of objects of array, it shows undefined
{type: "ADD_TO_CART", item: {…}}
item: {id: undefined, name: undefined, price: undefined, desc: undefined, type: undefined, …}
type: "ADD_TO_CART"
This is Menu.js
import React, { useState } from 'react';
import examples from './examples';
import './Menu.css';
import { useStateValue } from './StateProvider';
const Menu = ({ id, name, imgUrl, desc, price, type }) => {
const [dishes, setDishes] = useState(examples);
const [, dispatch] = useStateValue();
const addToCart = () => {
// add item to basket
dispatch({
type: 'ADD_TO_CART',
item: {
id,
name,
price,
desc,
type,
imgUrl,
},
});
};
return (
<div className='menu'>
<h1>Menu</h1>
<div className='menu__starters'>
<h1>Starters</h1>
{dishes.map((dish, index) => (
<div className='menu__column'>
<div className='menu__row'>
<div className='menu__card' key={index}>
<div className='menu__img'>
<img src={dish.imgUrl} alt='img' />
</div>
<div className='menu__desc'>
<div className='menu__name'>
<h2>{dish.name}</h2>
</div>
<div className='menu__description'>
<p>{dish.desc}</p>
</div>
<div className='menu__credentials'>
<div className='menu__price'>
<h5>Damage- ${dish.price}</h5>
</div>
<div className='menu__button'>
<button onClick={addToCart} key={index}>
Add to Cart ->
</button>
</div>
</div>
</div>
</div>
</div>
</div>
))}
</div>`
An array of objects is in another file examples.js which is exported. This is reducer.js
export const initialState = {
cart: [],
};
function reducer(state, action) {
console.log(action);
switch (action.type) {
case 'ADD_TO_CART':
// logic for adding item to cart
return { state };
break;
case 'REMOVE_FROM_CART':
//logic for removing item from cart
return { state };
break;
default:
return state;
}
}
export default reducer;`
Blockquote
Upvotes: 1
Views: 84
Reputation: 1728
It's undefined because those variables are not defined in addToCart
scope, you haven't passed any data to it.
You have to pass the dish into addToCart
<button onClick={()=>addToCart(dish)} ...>
And
const addToCart = ({ id, name, imgUrl, desc, price, type }) => {...}
Upvotes: 2