SHARE
TWEET

Untitled

a guest Jul 18th, 2019 57 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { useState, useEffect } from 'react'
  2.  
  3. export default function useJson(props) {
  4.   const [state, _setState] = useState({
  5.     data: props.initData,
  6.     error: null,
  7.     loading: true,
  8.   })
  9.  
  10.   const setState = patch => s => _setState({ ...s, ...patch })
  11.  
  12.   const refetch = (url = props.url, { autoFetch, ...opts }) => {
  13.     setState({ loading: true })
  14.     fetch(url, { ...props, ...opts })
  15.       .then(x => x.json())
  16.       .then(data => setState({ data, loading: false, error: null }))
  17.       .catch(e => setState({ error: e.message, loading: false }))
  18.   }
  19.  
  20.   useEffect(() => {
  21.     if ((props.autoFetch === undefined && props.url) || props.autoFetch) {
  22.       refetch()
  23.     }
  24.   }, [])
  25.  
  26.   return [state, refetch]
  27. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top