import useSWR, { SWRConfiguration, SWRResponse } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; type Response = SWRResponse; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); interface ServiceHooks { useList: (query?: string, options?: SWRConfiguration) => Response useItem: (id: string) => Response } type Hooks = Record; const hooks: Hooks = {}; const registerServiceHooks = (service: string): void => { if (hooks[service]) return; const useList = (query = '', options = {}): Response => { return useSWR(`/${service}${query}`, fetcher, options); }; const useItem = (_id: string): Response => { 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 }) as Item; return { ...result, data: item }; } return result; }; hooks[service] = { useItem, useList }; }; export { registerServiceHooks }; export default hooks;