aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils/hooks/use-data-from-api.tsx
blob: 5abcf09e5e62d82ea21371aafeae2ed596c656f3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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.
 */
export const useDataFromAPI = <T,>(
  fetcher: () => Promise<T>
): T | undefined => {
  const [data, setData] = useState<T>();

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

  return data;
};