Created
September 3, 2021 01:03
-
-
Save smoothness/08e10dd11a459e48ec3b23aa61803daa to your computer and use it in GitHub Desktop.
Fetching data in a useEffect that might be triggered several times.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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