Skip to content

Instantly share code, notes, and snippets.

@DanielFGray
Created July 6, 2019 18:18
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 DanielFGray/503ee07fdbae1eaf4597c77c3ef9308d to your computer and use it in GitHub Desktop.
Save DanielFGray/503ee07fdbae1eaf4597c77c3ef9308d to your computer and use it in GitHub Desktop.
useFetch hook
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