Skip to content

Instantly share code, notes, and snippets.

@dmmulroy
Last active November 15, 2019 03:50
Show Gist options
  • Save dmmulroy/721a15b725493e516101269a6365bc70 to your computer and use it in GitHub Desktop.
Save dmmulroy/721a15b725493e516101269a6365bc70 to your computer and use it in GitHub Desktop.
Simple no nonsense useFetch hook for fetching JSON.
import React from 'react';
const defaultOpts = {};
// Technically works more like useFetchLatest
// If you supply opts make sure that it is memoized
export function useFetch(url, opts = defaultOpts) {
const [{ data, error, fetching }, setState] = React.useState({
data: null,
error: null,
fetching: false
});
const id = React.useRef(0);
const refetch = React.useCallback(() => {
const requestId = ++id.current;
setState(state => ({ ...state, fetching: true }));
fetch(url, opts)
.then(res => res.json())
.then(data => {
if (requestId === id.current) {
setState({ data, error: null, fetching: false });
}
})
.catch(error => {
if (requestId === id.current) {
setState({ data: null, error: error.message, fetching: false });
}
});
}, [url, opts]);
React.useEffect(() => {
refetch();
}, [refetch]);
return { data, error, fetching, refetch };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment