I'm getting an error that 'exampleState' is not iterable, but why?
Say that I have a state variable which holds a simple array of objects
const [exampleState, setExampleState] = useState([
{
id: 1,
name: 'John'
},
{
id: 2,
name: 'Mary'
}
])
I want to change the values of these objects conditionally. I thought a loop with a conditional inside would be an easy way to do this. I tried the following...
for (let item of exampleState) {
if (item.name === 'John') {
setExampleState({...exampleState, name: 'Michael'})
}
}
but I get the following error: 'TypeError' exampleState is not iterable
How should I do this instead?
CodePudding user response:
you can use map
for that like this
setExampleState(state => state.map(s => s.name === 'John'?{...s, name:'Michael' }: s))
if you set the state in a loop you always overwriting your array with a single element
CodePudding user response:
Firstly, the usual way to go about this, in general, is to update the state the least times you need to. Secondly, you are trying to update the value of the state with an object, whereas it is a list when it's initialized. This can be achieved using a single update:
setExampleState(...exampleState.map((user) => {
if (user.name === 'John') {
user.name = 'Michael';
}
return user;
}));
CodePudding user response:
You should check immer library, it is awesome for operating immutable data structures like that.