I've seen this question and it's helped with my understanding of how to set state correctly, but I'm struggling with the correct format of testing state based on a variable.
For example, I have this setState
function call with a newItem
variable:
addToSandwich(newItem){
setState(prevState => {
return { sandwichItems: {...prevState.sandwichItems, [newItem]: true} };
});
}
And assuming the current state looks like this:
sandwichItems: {
meat: true,
cheese: true,
tomato: false
}
With var newItem = "tomato";
It would result in this:
sandwichItems: {
meat: true,
cheese: true,
tomato: true
}
But I am unable to test for newItem with:
var newItem = "tomato";
if (this.state.sandwichItems.newItem === true) {//whatever}
I would have to do:
if (this.state.sandwichItems.tomato === true) {//whatever}
How do I test for a value in state based on a variable's value?