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?

2
  • If you want to view the state from your browser, I'd recommend checking out the React DevTools Commented Aug 1, 2018 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 Commented Aug 1, 2018 at 19:15

1 Answer 1

1

This is what you want:

var newItem = "tomato";
if(this.state.sandwichItems[newItem] === true { }
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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 that looks right. But you would need to show me an example of the object.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.