import useSWR, { responseInterface } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; type Response = responseInterface; export interface Product { _id: string; name: string; description: string; price: number; quantity: number; specs: any; createdAt: string; updatedAt: string; } const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); export const useProducts = (options = {}): Response => { return useSWR('/products', fetcher, options); }; export const useProduct = (_id: string): Response => { const { data: preloadedProducts } = useProducts({ revalidateOnMount: false }); const result = useSWR(`/products/${_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 product = _.find(preloadedProducts, { _id }); return { ...result, data: product }; } return result; };