Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

334
Views
React - state contains array of objects. setState with conditional

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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;
}));
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!