summaryrefslogtreecommitdiff
path: root/src/hooks/useAPIClient.ts
blob: fd3ee19f4fea0d81f8faf1465df92d5c23a653e2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import useSWR, { SWRConfiguration, SWRResponse } from 'swr';
import _ from 'lodash';
import { get } from '../requests';

type Response<T> = SWRResponse<T, Error>;

const fetcher = (endpoint: string) => get(endpoint).then(response => response.data);


interface ServiceHooks<T = any> {
  useList: (query?: string, options?: SWRConfiguration) => Response<T[]>
  useItem: (id: string) => Response<T>
}

type Hooks = Record<string, ServiceHooks>;

const hooks: Hooks = {};

const registerServiceHooks = <Item = any>(service: string): void => {
  if (hooks[service]) return;

  const useList = (query = '', options = {}): Response<Item[]> => {
    return useSWR(`/${service}${query}`, fetcher, options);
  };

  const useItem = (_id: string): Response<Item> => {
    const { data: preloadedItems } = useList('', { revalidateOnMount: false });
    const result = useSWR(_id && `/${service}/${_id}`, fetcher);
    if (!result.data && result.isValidating) {
      // If we are waiting for the first result, check if we can maybe
      // get the data from already cached list for the time-being
      const item = _.find(preloadedItems, { _id });
      return { ...result, data: item } as Response<Item>;
    }
    return result;
  };

  hooks[service] = { useItem, useList };
};

export { registerServiceHooks };
export default hooks;