I'm trying to make a dynamic burger builder in ReactJS. As soon as the homepage opens, I get an error like this:
TypeError: Cannot read property 'name' of undefined
IngredientsMenuItem
/src/components/IngredientsMenu/IngredientsMenuItem.js:18
15 | return (
16 | <ItemWrapper>
17 | <ItemContent>
> 18 | <h3>{item.ingredient.name}</h3>
| ^ 19 | <h4>{item.ingredient.price}</h4>
20 | <Counter
21 | value={item.qty}
I keep my burger in a context.
My ingredients file:
export const ingredients= [
{
name:"salad",
price:0.5,
},
{
name:"cheese",
price:0.4,
},
{
name:"meat",
price:1.3,
},
];
My home page:
const Home = () => {
const {burger,updateBurger} = useContext(BurgerContext);
return (
<div>
{!burger.length && updateBurger(buildBurger(ingredients))}
<Burger/>
<IngredientsMenu
ingredients={ingredients}
/>
</div>
)
}
export default Home
My buildBurger function:
export const buildBurger = (ingredients) => {
return [
ingredients.map((ingredient) => (
{
qty:0,
ingredient: ingredient
}
))
]
}
I did this to create a template for ingredients with values 0 in the initial state.
My IngredientsMenu:
const IngredientsMenu = ({ingredients}) => {
const {burger, updateBurger} = useContext(BurgerContext);
return (
<>
<Wrapper>
{burger.map((item) => (
<IngredientsMenuItem
item={item}
/>
))}
</Wrapper>
</>
)
}
export default IngredientsMenu
My IngredientsMenuItem:
const IngredientsMenuItem = ({item) => {
const {burger, updateBurger} = useContext(BurgerContext);
const handleIncrement = (burgerItem) => {
}
const handleDecrement = (burgerItem) => {
}
return (
<ItemWrapper>
<ItemContent>
<h3>{item.ingredient.name}</h3>
<h4>{item.ingredient.price}</h4>
<Counter
value={item.qty}
onIncrement={() => handleIncrement(item)}
onDecrement={() => handleDecrement(item)}
/>
</ItemContent>
</ItemWrapper>
)
}
export default IngredientsMenuItem
I couldn't see where my fault was. Is there anyone who can help?
BurgerContext... Are you?}afteritemhere:const IngredientsMenuItem = ({item) => {returnstatement:{!burger.length && updateBurger(buildBurger(ingredients))}