Created
July 15, 2021 22:46
-
-
Save Loonz806/ca6055839763fd41421ca83e5515d498 to your computer and use it in GitHub Desktop.
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
import { useState, useEffect } from "react"; | |
const CACHE = {}; | |
export default function useStaleRefresh(url, defaultValue = []) { | |
const [data, setData] = useState(defaultValue); | |
const [isLoading, setLoading] = useState(true); | |
useEffect(() => { | |
// cacheID is how a cache is identified against a unique request | |
const cacheID = url; | |
// look in cache and set response if present | |
if (CACHE[cacheID] !== undefined) { | |
setData(CACHE[cacheID]); | |
setLoading(false); | |
} else { | |
// else make sure loading set to true | |
setLoading(true); | |
setData(defaultValue); | |
} | |
// fetch new data | |
fetch(url) | |
.then((res) => res.json()) | |
.then((newData) => { | |
CACHE[cacheID] = newData; | |
setData(newData); | |
setLoading(false); | |
}); | |
}, [url, defaultValue]); | |
return [data, isLoading]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment