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

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

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 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