Reputation: 1048
I have a simple React project that in short is like a little restaurant. And the restaurant can only serve certain dishes when all ingredients are available.
So I wrote something to check for each dish that all ingredients are available / true. But within my JSX I am getting the following error TypeError: Cannot read property 'status' of undefined
(screenshot provided).
However where you can see I have a console.log at // 1.
, the status property is defined.
Link to my public repo: https://github.com/danny-faith/dynamenu/tree/update/ingre-object
Use update/ingre-object
branch
Ingredients object
const ingredients = {
egg: {
status: true
},
beef: {
status: false
}
}
Menu object
const food = {
item1: {
name: "Spaghetti Carbonara",
desc: "With egg yolk and guanciale",
price: 1724,
ingredients: ['spaghetti','egg','pancetta'],
status: "available"
}, ...
}
Code insinde JSX
{
Object.keys(this.state.menu).map(key => {
console.log(this.state.ingredients['egg'].status); // 1.
if (menu[key].ingredients.some(val => this.state.ingredients[val].status === true) ){
return <MenuItem key={key} data={menu[key]} />
}
})
}
Upvotes: 0
Views: 292
Reputation: 4928
I dont see where you set your state , but this error can simply be avoided by adding checks state.ingredients
like below.
if (menu[key].ingredients
.every(val => {
return this.state.ingredients[val] ?
this.state.ingredients[val].status === true :
false;
})){
return <MenuItem key={key} data={menu[key]} />
}
A better practice would be to take the if condition to a separate function.
EDIT, added extra closing parenthesis to complete .some() function.
Upvotes: 1
Reputation: 66
Since you are mapping an object maybe the problem is not on the specific ingredient that you log.
I think Cannot read property 'status' of undefined
referred to this.state.ingredients[val].status
depends on a val
that is not defined on your ingredients
object nested in one of the menu
properties.
You probably have a menu ingredient that is not present in the ingredients.
[EDIT]
Looking at your repo I see:
item1: {
name: "Spaghetti Carbonara",
desc:
"With egg yolk and guanciale",
price: 1724,
ingredients: ['egg','spaghetti','pancetta'],
status: "available"
},
...
And your ingredients are:
const ingredients = {
egg: {
status: true
},
beef: {
status: false
}
}
So, for instance, ingredients['spaghetti']
or ingredients['pancetta']
are undefined.
Upvotes: 1