Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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]
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement