Reputation: 498
This is my code here : XXXXX sorry code no longer available will include soon.
What I would like to happen is when I click a button the 'index' of each object is passed like this:
const priceShown = product[evenIndex].price;
But when the pages loads I get an error saying price
is undefined :(
I know its something to do with the data not existing yet (I have little knowledge as to why this is a thing so if you could also explain this would be a great bonus too!) .
To check if the data is there before priceShown
I wrote this:
if (evenIndex !== null) {
return evenIndex;
} else {
console.log('no data');
};
This returns the no data
part of the statement always as you can't pass an index (evenIndex
) unless you click on a button, so price
will always be undefined? Unless its undefined for another reason of which I do not know.
Any Help?
Upvotes: 1
Views: 229
Reputation: 112787
You can check if product[evenIndex]
is set first, and then take out the price
if it is. This way no price will be rendered until an index has been selected.
const priceShown = product[evenIndex] && product[evenIndex].price;
Upvotes: 3
Reputation: 757
You need to verify whether evenIndex
even exists before trying to access the product
array. You can even get rid of evenIndex as it serves no use in your example.
const priceShown =
this.state.evenSelected == null
? "No data"
: product[this.state.evenSelected].price;
Here's an updated version of the code you linked: https://codesandbox.io/s/kmw7npp7z5
Upvotes: 0