Last active
November 15, 2019 03:50
-
-
Save dmmulroy/721a15b725493e516101269a6365bc70 to your computer and use it in GitHub Desktop.
Simple no nonsense useFetch hook for fetching JSON.
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
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