dad living in Switzerland 🇨🇭 mainly working on typescript, css and compiler related frontend topics - maybe you know me from html-webpack-plugin, text-box-trim or next-yak
Your useEffect is using an async function which can be problematic.
If your component unmounts or your effect dependencies like [url, options] change while your ajax is running the "old" effect run will still manipulate the state.
The worst possible case is that the first call is slower than the second ajax call and your state will end up with wrong data.
Here is a small trick to prevent those bugs by checking after your awaits if the effect is still running:
useEffect(()=>{letisEffectRunning=true;asyncfunctionfetchData(){try{constres=awaitfetch(url,options);constjson=awaitres.json();// Stop here if the effect is outdated:if(!isEffectRunning){return}/* ... */}catch(e){/* ... */}}/* ... */return()=>{isEffectRunning=false}},[url,options]);
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Your
useEffectis using an async function which can be problematic.If your component unmounts or your effect dependencies like
[url, options]change while your ajax is running the "old" effect run will still manipulate the state.The worst possible case is that the first call is slower than the second ajax call and your state will end up with wrong data.
Here is a small trick to prevent those bugs by checking after your awaits if the effect is still running: