Search code examples
javascriptreactjsreact-hooksuse-state

React useState - update all object values to true


I have defined an object as follows in a file:

export const items = {
  first: false,
  second: false,
  third: false
}

I'm using it in a component as follows:

import { items } from 'file';
const [elements, setElements] = useState(items);

I have a method which gets called when a button is clicked - the method should change the all the values in elements to true

Using the following changes the values but it does not trigger a re-render of the component (which is what I need)

Object.keys(elements).forEach(element => elements[element] = true);

How can I use setElements to update all the values in elements?


Solution

  • The problem you are facing is that you are mutating the state object, which means that at the end, prevState === nextState and React bails out of rendering. An option is to use a new object and copy the props like this, using the same combo of Object.keys and forEach but adding an extra step:

    setState(prevState => {
      const nextState = {}
      Object.keys(prevState).forEach(key => {
        nextState[key] = true
      })
      return nextState
    })