Last active
November 27, 2020 09:37
-
-
Save michielvaneerd/a8c7801510c3007a25db41910a16ca5f to your computer and use it in GitHub Desktop.
ReactJS hook for fetch an API response and store it to the cache
This file contains hidden or 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
/** | |
* The useFetchCache hook: fetch API response and save it in the cache. | |
* The next time it uses the cached response. | |
**/ | |
const _cache = {}; | |
export default function useFetchCache(key) { | |
const [data, setData] = useState((key in _cache) ? _cache[key] : null); | |
const [error, setError] = useState(null); | |
useEffect(function() { | |
if (data) { | |
return; | |
} | |
(async function() { | |
try { | |
const response = await fetch(key); | |
if (!response.ok) { | |
throw Error("Response is not ok"); | |
} | |
const json = await response.json(); | |
_cache[key] = json; | |
setData(json); | |
} catch (err) { | |
setError(err); | |
} | |
}()); | |
}, [key, data]); | |
return [ data, error ]; | |
} | |
/** | |
* You can use the hook like this in your React component: | |
**/ | |
function App() { | |
const [ data, responseError ] = useFetchCache("https://jsonplaceholder.typicode.com/users"); | |
if (responseError) { | |
return <div>Error: {responseError.toString()}</div> | |
} | |
if (!data) { | |
return <div>Loading data...</div> | |
} | |
const userList = data.map(function(user) { | |
return <li key={user.id}>{user.name}</li> | |
}); | |
return ( | |
<ul> | |
{userList} | |
</ul> | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment