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?
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);
});
}, []);