Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

336
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda