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

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

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 Denunciar

0

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

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