Skip to content

Instantly share code, notes, and snippets.

@smoothness
Created September 3, 2021 01:03
Show Gist options
  • Save smoothness/08e10dd11a459e48ec3b23aa61803daa to your computer and use it in GitHub Desktop.
Save smoothness/08e10dd11a459e48ec3b23aa61803daa to your computer and use it in GitHub Desktop.
Fetching data in a useEffect that might be triggered several times.
useEffect(() => {
let isSubscribed = true;
// declare the async data fetching function
const fetchData = async () => {
// get the data from the api
const data = await fetch(`https://yourapi.com?param=${param}`);
// convert the data to json
const json = await response.json();
// set state with the result if `isSubscribed` is true
if (isSubscribed) {
setData(json);
}
}
// call the function
fetchData()
// make sure to catch any error
.catch(console.error);;
// cancel any future `setData`
return () => isSubscribed = false;
}, [param])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment