Created
August 2, 2020 13:25
-
-
Save dnshko/ce0cb4bec9b3ab6975c07af889ead5fc to your computer and use it in GitHub Desktop.
useRef
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 useFetch = (url) => { | |
const cache = useRef({}); | |
const [status, setStatus] = useState('idle'); | |
const [data, setData] = useState([]); | |
useEffect(() => { | |
if (!url) return; | |
const fetchData = async () => { | |
setStatus('fetching'); | |
if (cache.current[url]) { | |
const data = cache.current[url]; | |
setData(data); | |
setStatus('fetched'); | |
} else { | |
const response = await fetch(url); | |
const data = await response.json(); | |
cache.current[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