0

Trying to update an objects state via the useState hook but it does not seem to be working. Just wondering if anyone can spot what I'm doing wrong here:

This is my useState:

const [selectState, setSelectState] = React.useState({
  level1: 0,
  level2: 0,
  level3: 0,
});

Component where I'm trying to update State:

<Button
   onClick={() => setSelectState({ ...selectState, level: 1 })}
   selected={selectState === 1}
   text="Blue"
 />

1 Answer 1

1

I can see couple of problems in your code:

  • setSelectState({ ...selectState, level: 1 }) - you are updating the level property but it is not present in the state. So you are adding a new property in the state instead of updating the existing one.

  • selected={selectState === 1} - selectedState is an object. So you are comparing a number with an object and because of strict equality operator (===), the following condition:

    selectState === 1
    

    will never evaluate to true.

Sign up to request clarification or add additional context in comments.

Comments

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.