Skip to content

Instantly share code, notes, and snippets.

@michielvaneerd
Last active November 27, 2020 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michielvaneerd/a8c7801510c3007a25db41910a16ca5f to your computer and use it in GitHub Desktop.
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
/**
* 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