0

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?

Jaich
  • 134
  • 1
  • 11
  • If you want to view the state from your browser, I'd recommend checking out the [React DevTools](https://chrome.google.com/webstore/detail/fmkadmapgofadopljbjfkapdkoienihi) – Jon Warren Aug 01 '18 at 19:12
  • @JonWarren I currently use the React DevTools and it's been one of the most useful tools for my web dev projects – Jaich Aug 01 '18 at 19:15

1 Answers1

1

This is what you want:

var newItem = "tomato";
if(this.state.sandwichItems[newItem] === true { }
Hoyen
  • 2,511
  • 1
  • 12
  • 13
  • This worked, thank you! I'm going to leave the question up for a bit before accepting, but this is the answer I was looking for. – Jaich Jul 16 '18 at 19:08
  • Just by chance, would you know the syntax to go another object deeper? As if tomato was an object as well? Would it be (this.state.sandwichItems[newItem][value])? – Jaich Jul 24 '18 at 19:49
  • 1
    @Jaich that looks right. But you would need to show me an example of the object. – Hoyen Jul 24 '18 at 20:38