I have 2 different useEffect:
useEffect(() => {
return () => {
setElements(undefined);
};
}, [elementParam]);
useEffect(() => {
if (currentlyFetchedElements) {
setElements(previouslyFetchedElements => ({ ...previouslyFetchedElements, ...currentlyFetchedElements }));
}
}, [currentlyFetchedElements]);
- The idea of the 1st
useEffect
is to "restart" theelements
state, wheneverelementParam
updates. - When
elementParam
updates, it also triggers and API call that updatescurrentlyFetchedElements
The problem:
If I mess with elementParam
long enough, there’s a point where the currentlyFetchedElements
API call is cached, and the 2nd use effect takes place before the 1st one, and i see elements
as undefined
when they’re not.
NOTE: I don’t want to setElements(undefined);
always, just if elementParam it’s updated, bc i’m using elements
to accumulate the API responses(that’s why i have 2 different useEffects
)
How can i fix this?
The only work around i’ve found so far is adding a setTimeout
to the 2nd useEffect
to make sure it takes place after the 1st one but i know there should be a better way
2
Answers
You can use one
useEffect
instead!Check the following code:
Personally I would use one useEffect that depends on both
elementParam
andcurrentlyFetchedElements
.That way, this effect is fired when either of those dependencies change. Here you can use a boolean
useState
as a flag that ensures that the second method fires only after the first one is done, like: