aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-data-from-api.tsx
blob: 70829412755cca1a22197da9eca7addfae114b0f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import { useEffect, useState } from 'react';

/**
 * Fetch data from an API.
 *
 * This hook is a wrapper to `setState` + `useEffect`.
 *
 * @param fetcher - A function to fetch data from API.
 * @returns {T | undefined} The requested data.
 */
const useDataFromAPI = <T extends unknown>(
  fetcher: () => Promise<T>
): T | undefined => {
  const [data, setData] = useState<T>();

  useEffect(() => {
    fetcher().then((apiData) => setData(apiData));
  }, [fetcher]);

  return data;
};

export default useDataFromAPI;