Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

343
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda