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

116
Vistas
Updating an array of objects with setTimeout with react and state

I have an array of objects, and each object has a false property value by default:

 const [items, setItems] =  useState([ { key: 1, has_x: false }, { key: 2, has_x: false }, { key: 3, has_x: false } ]);

Which is passed down to child components:

<Item key={item.key} hasX={item.has_x} />

In the parent component, I have a "Check All" button:

<button onClick={handleCheckAll}>Check All</button>

Which would loop through every item and modify item.has_x to true.

In the child components, there's also a "Check" button, but instead of checking all items, it just checks and sets that one specific item has_x to true.

I think I would know how to do each one. For the "Check All" function, I'd create a shadow copy, set the value, and then once the loop is done, set the state. For the child button, I really just need a useState there for it.

However, I am stuck on the "Check All" button because I'd like to have ui updates as has_x for each item gets updated and a setTimeout, as the actual functionality of check all will be expensive and needs about 200-300ms wait time for each check. Imagine a button's text changes to a checkmark as the function loops through each item.

Here's my attempt but the UI doesn't get updated and I only am setting the state once it's done:

const checkAllItems = () => {
    let temp = [...items];
    temp.map((item, index) => {
        setTimeout(() => {
            let tempEl = {...tempState[index]};
            if (tempEl) item.has_x = true;
        }, index * 200)
    })
    setItems(temp)
}

My only idea of how to do this is to use refs and loop through the refs to run a function in each child component that will do this, but I feel like there's a correct way to go about this. How is it possible?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I can't imagine needing a timeout for updating state. I am certain if you tweak your check-all items code a bit you won't need the timeout. You can use a functional state update to enqueue the state updates and correctly update from the previous state instead of the state value closed over in callback scope.

const checkAllItems = () => {
  setItems(items => items.map(item => ({
    ...item,
    has_x: true,
  })));
};

This shallow copies the previous items state into a new array, and then you also shallow copy each item element and update the has_x property.

Update

If you are making backend API requests per checked update in items then I suggest doing this in a useEffect lifecycle hook. Loop over each item and enqueue the network request in a setTimeout. It's basically splitting out the timeout logic (you had previously) from the state update.

useEffect(() => {
  items.forEach((item, index) => {
    setTimeout(() => {
      // make API request with `item`
    }, index * 200);
  });
}, [items]);

/update

I also don't recommend the child components to also have any "checked" state, you want a single source of truth as to the checked status of your items array. Pass a callback to the children for them to update their checked status in the parent component's state.

It could look something like this:

const updateStatus = (key, value) => {
  setItems(items => items.map(item => item.key === key
    ? {
      ...item,
      has_x: value,
    }
    : item
  ));
};

...

<Item key={item.key} hasX={item.has_x} updateX={updateStatus} />
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