Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

90
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!