DEV Community

Discussion on: React Custom Hook - useFetch

Collapse
 
karunamaymurmu profile image
Karunamay Murmu

How can we call the custom hook on button click event?

Collapse
 
alextrastero profile image
alextrastero

You would need a new hook in that case, one that returns the actual function instead of calling it inside useEffect, something like:

function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(null);
  const [error, setError] = useState(null);

  const myFetch = useCallback(() => {
    setLoading('loading...')
    setData(null);
    setError(null);
    axios.get(url).then(res => {
      setLoading(false);
      // checking for multiple responses for more flexibility 
      // with the url we send in.
      res.data.content && setData(res.data.content);
      res.content && setData(res.content);
    })
    .catch(err => {
      setLoading(false)
      setError('An error occurred. Awkward..')
    })
  }, [url]);

  return { myFetch, data, loading, error }
}
Enter fullscreen mode Exit fullscreen mode