Created
August 2, 2020 13:22
-
-
Save dnshko/1a7ac189fd61d3c92f6ff4c76a29be8c to your computer and use it in GitHub Desktop.
Fetched Data
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
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