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
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.