2

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?

1
  • 1
    You should be able to do for ... in instead of for ... of here I think and the rest should just work. Commented Jun 16, 2022 at 21:17

3 Answers 3

1

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;
}));
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

You should check immer library, it is awesome for operating immutable data structures like that.

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.