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

166
Visualizações
set an array with useState doesn't change the result

I have a list of data like this:

data = [
  {
    id:1,
    name: "boo"
  },
  {
    id:1,
    name: "boo"
  }
]

I initialize it with react UseState like follows:

const [items, setItems] = useState(data)

And I map this in my react code and visualize them.

If I want to delete one I do it with the following function:

  const deleteItem = async (id) => {
    console.log('BEFORE- - - ->', items);
    // this functions calls an api to delete the item
    await deleteItem({ id });
    setItems((oldItems) =>
      oldItems.filter(({ id }) => id !== commentId)
    );
    console.log('AFTER- - - ->', items);
  };

Graphically the component with the deleted item disappears, but actually the second console.log prints the same thing as the first log. In this case if I delete the element with id:1 I will get the same log while I see graphically that the element disappears. This causes a problem with indexing if I want to delete more than one item.

Which do you think is the problem? has I to do it into one useEffect?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Setting state is an asynchronous action. If you put a console outside of that function, on the next re-render you will see your state updated correctly (just like you've seen your item disappear visually).

about 4 years ago · Juan Pablo Isaza Relatório

0

This happens because setState is asynchronous so the state really changes after you console.log

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