Advertisement
Guest User

Untitled

a guest
Jul 18th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.70 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement