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

261
Views
Why filtering isn't working in React and JS. Help me to find a mistake

Can not understand why filter is not working. The function get an object. If there is the same object in the state, the function delete this object from the state. If not, add to the state. The problem is that the object rewrites the state, but not add it to the state.

For example, object {a: 1, b: 2}

const [products, setProducts] = useState<any[]>([]);

const addObject = (data) => {
    const sameData = !!products.find((item) => item.id === data.id);
    const deleteData = products.filter((item) => item.id !== data.id);
    const newData = sameData ? deleteData : [...products, data]; 
    return setCheckedRoles(newData);
  };

As a result I get not [{a: 1, b: 2}, {a: 2, b: 4}, {a: 8, b: 3}]; but only one object that come to function [{a: 1, b: 2}]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You want deleteData to run only when sameData is true, but instead it is running the moment you're defining it. (remember that filter() is being invoked)

To get the expected behaviour move the deleteData to be a function and execute it as per your wish

const [products, setProducts] = useState<any[]>([]);

const deleteData = (products) => products.filter((item) => item.id !== data.id);

const addObject = (data) => {
    const sameData = !!products.find((item) => item.id === data.id);
    const newData = sameData ? deleteData(products) : [...products, data]; 
    return setCheckedRoles(newData);
};

Also please find a better name for the function addObject :)

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!