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

107
Views
Filter Inside UseEffect React Not Working

Im using the .filter() method on an object inside of a useEffect() method to filter out certain arrays out by name if they exist in a second object. I need to get the difference of arrays back into a useState() method. Im using the following and works outside the useEffect() method:

useEffect(() => {
  getDBData().then( (r) => { setAnotherObj(r); });
  getAPICall().then((r) => {
    let result = r.filter(
      (o1) => !anotherObj.filter((o2) => o1.name === o2.name)
    );
    setOption(result);
  });
}, []);

Now that works outside of the useEffect method when I add it to an event like onClick, but not inside, it might work one time then it doesn't at all. What am I missing about the useEffect method that I need to know why the filtering isn't being done?

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

0

Replace second filter with find. !anotherObj.filter(o2 => o1.name === o2.name) will always return false, be it has elements or not.

There is no dependency array in the in the useEffect, so whenever there is a state change, this useEffect gets triggered again.

Finding A-B, filter all the elements of A that are not in B. r.filter(o1 => anotherObj.find(o2 => o1.name !== o2.name)); With this it removes all the elements that are common in A and B. And leaves out only elements in A.

Update as follows,

useEffect( () => { 
  getAPICall().then( (r) => { 
   const result = r.filter(o1 => anotherObj.find(o2 => o1.name !== o2.name));         
    setOption(result);  
  });
}, []);
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!