Skip to content Skip to sidebar Skip to footer

Fetching Data With Hooks

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 other co

Solution 1:

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

constidentity = x => x

constuseAsync = (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 -

constMyComponent = () => {
  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 -

constfetchJson = (url) =>
  axios.get(url).then(r => r.json())

constuseJson = (url) =>
  useAsync(fetchJson, [url])

constMyComponent = () => {
  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><Itemsitems={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.

Post a Comment for "Fetching Data With Hooks"