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

92
Visualizações
How to append to state array in React hooks?

I have a state set as

const [filteredProducts, setFilteredProducts] = useState([]);

I want to be able to append to the end of that state. I am currently trying

products.forEach((product) => {
        if (product.category === category) {
          setFilteredProducts([...filteredProducts, product]);
        }
      });

It it looping through the products array correctly. I can even log the product after the setFilteredProducts and it logs the correct ones I want. I am calling this with an onClick.

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

0

Find all the products you want to add:

const productsToAdd = products.filter(product => product.category === category)

Then append them

setFilteredProducts((currentFilteredProducts) => ([...currentFilteredProducts, ...productsToAdd]));

The issue with your example is that filteredProducts may get stale after the first iteration. setFilteredProducts will not run synchronously, and filteredProducts keep the original value, until the re-render happen.

about 4 years ago · Juan Pablo Isaza Relatório

0

You would only append the last match to the existing filteredProducts array.

You can add all matches like so:

setFilteredProducts([...filteredProducts, ...products.filter((product) => product.category === category)]);
about 4 years ago · Juan Pablo Isaza Relatório

0

I'd recommend you do this in 2 steps:

Create an array of the new products you plan to add

let productsToAdd = [];

products.forEach((product) => {
    if (product.category === category) {
      productsToAdd.push(product);
    }
  });

Then combine the arrays and set state

setFilteredProducts([...filteredProducts, ...productsToAdd]);
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