Skip to content

Instantly share code, notes, and snippets.

@dnshko
Last active August 2, 2020 13:32
Show Gist options
  • Save dnshko/2d14a7a8f8cffeb085ff221333b43592 to your computer and use it in GitHub Desktop.
Save dnshko/2d14a7a8f8cffeb085ff221333b43592 to your computer and use it in GitHub Desktop.
useEffect
useEffect(() => {
let cancelRequest = false;
if (!url) return;
const fetchData = async () => {
dispatch({ type: 'FETCHING' });
if (cache.current[url]) {
const data = cache.current[url];
dispatch({ type: 'FETCHED', payload: data });
} else {
try {
const response = await fetch(url);
const data = await response.json();
cache.current[url] = data;
if (cancelRequest) return;
dispatch({ type: 'FETCHED', payload: data });
} catch (error) {
if (cancelRequest) return;
dispatch({ type: 'FETCH_ERROR', payload: error.message });
}
}
};
fetchData();
return function cleanup() {
cancelRequest = true;
};
}, [url]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment