Created
July 6, 2019 18:18
-
-
Save DanielFGray/503ee07fdbae1eaf4597c77c3ef9308d to your computer and use it in GitHub Desktop.
useFetch hook
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 { useState, useEffect } from 'react' | |
export default function useJson(props) { | |
const [state, _setState] = useState({ | |
data: props.initData, | |
error: null, | |
loading: true, | |
}) | |
const setState = patch => s => _setState({ ...s, ...patch }) | |
const refetch = (url = props.url, { autoFetch, ...opts }) => { | |
setState({ loading: true }) | |
fetch(url, { ...props, ...opts }) | |
.then(x => x.json()) | |
.then(data => setState({ data, loading: false, error: null })) | |
.catch(e => setState({ error: e.message, loading: false })) | |
} | |
useEffect(() => { | |
if ((props.autoFetch === undefined && props.url) || props.autoFetch) { | |
refetch() | |
} | |
}, []) | |
return [state, refetch] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment