Fetching data with hooks

后端 未结 1 655
南笙
南笙 2021-01-23 11:34

I\'m having a hard time to wrap my head around the best way to fetch data from an API only once (and when it\'s first requested) and then storing the result for reuse and/or oth

相关标签:
1条回答
  • 2021-01-23 11:57

    I imagine you could write some abstraction around this using custom hooks -

    const identity = x => x
    
    const useAsync = (runAsync = identity, deps = []) => {
      const [loading, setLoading] = useState(true)
      const [error, setError] = useState(null)
      const [result, setResult] = useState(null)
    
      useEffect(_ => {
        Promise.resolve(runAsync(...deps))
          .then(setResult, setError)
          .finally(_ => setLoading(false))
      }, deps)
    
      return { loading, error, result }
    }
    

    You're excited so you start using it right away -

    const MyComponent = () => {
      const { loading, error, result:items } =
        useAsync(_ => {
          axios.get("path/to/json")
            .then(res => res.json())
        }, ...)
    
      // ...
    }
    

    But stop there. Write more useful hooks when you need them -

    const fetchJson = (url) =>
      axios.get(url).then(r => r.json())
    
    const useJson = (url) =>
      useAsync(fetchJson, [url])
    
    const MyComponent = () => {
      const { loading, error, result:items } =
        useJson("path/to/json")
    
      if (loading)
        return <p>Loading...</p>
    
      if (error)
        return <p>Error: {error.message}</p>
    
      return <div><Items items={items} /></div>
    }
    

    Conveniently useEffect will only re-run the effect when the dependencies change. However if you expect to have expensive queries that you wish to handle with finer control, look at useCallback and useMemo.

    0 讨论(0)
提交回复
热议问题