Skip to content

Instantly share code, notes, and snippets.

@dnshko
Created August 2, 2020 13:22
Show Gist options
  • Save dnshko/1a7ac189fd61d3c92f6ff4c76a29be8c to your computer and use it in GitHub Desktop.
Save dnshko/1a7ac189fd61d3c92f6ff4c76a29be8c to your computer and use it in GitHub Desktop.
Fetched Data
const cache = {};
const useFetch = (url) => {
const [status, setStatus] = useState('idle');
const [data, setData] = useState([]);
useEffect(() => {
if (!url) return;
const fetchData = async () => {
setStatus('fetching');
if (cache[url]) {
const data = cache[url];
setData(data);
setStatus('fetched');
} else {
const response = await fetch(url);
const data = await response.json();
cache[url] = data; // set response in cache;
setData(data);
setStatus('fetched');
}
};
fetchData();
}, [url]);
return { status, data };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment