import useSWR, { responseInterface } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; import services from '../services'; type Response = responseInterface; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); const createServiceHooks = (service: string) => { const useList = (options = {}): Response => { return useSWR(`/${service}`, 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 }); return { ...result, data: item } as Response; } return result; }; return { useItem, useList }; }; // Products export interface Product { _id: string; name: string; description: string; price: number; quantity: number; specs: any; createdAt: string; updatedAt: string; } // Contractors export interface Contractor { _id: string; name: string; fullName: string; vatId: string; type: string; debt: number; } const hooks = services.reduce((acc, { route }) => { return _.set(acc, route, createServiceHooks(route)); }, {}); export default hooks as any;