Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

have array of objects stored in useState. doesn't update when using the updater function

This is a simplified example of some code I have.

I have a some state, that stores an array of objects

const [characters,setCharacters] = useState([
   {
     val:1,
     bool:false
   },
   {
     val:2,
     bool:false
   },
   {
     val:3,
     bool:false
   },
])

I want to update one of the bool‘s to true. I then do

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

setCharacters(prev => {
  prev[2].bool = true
  return prev
})

But it doesn’t work. Can anyone explain why?

>Solution :

You need to set a new reference. That is how react detect updates for state variables which are objects.

setCharacters(prev => {
  let prev2=[...prev]
  prev2[2] ={ ...prev2[2], bool : true};
  return prev2;
})

Above code, creates a new reference for the array and the object at 2 index.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading