There is an input field that will update a state called q
to whatever the user enters, and the code inside useEffect
will do a search with q
.
If the length of q
is <= 2, then I need to empty the stuff
state.
I am having an issue where the changes from setStuff(thing)
from the previous useEffect
render, is overwriting setStuff([])
happening in the current useEffect
render
useEffect(()=>{
if (q.length > 2) {
fetchSomething(q).then(thing => setStuff(thing))
} else {
setStuff([]);
}
}, [q]);
3
Answers
If you don’t have a a system setup where you can easily cancel requests you can just ignore the response you are getting back when you no longer need it.
This is untested, but this should work just fine.
I think the problem is that you are not canceling the previous fetch request when the
q
changes, so you might end up with a race condition where the old request finishes after the new one and overwrites the state. You can try to use an abort controller to cancel the previous request when theq
value changes, like this:You can see the whole example here.
If you are using axios, you can set the request like this:
the recommended way is to use a cleanup callback to clean states and listeners when the component unmount (for a re-rendring in you case)