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

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

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 Denunciar

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 Denunciar

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