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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
|
import useSWR, { responseInterface } from 'swr';
import _ from 'lodash';
import { get } from '../requests';
type Response<T> = responseInterface<T, Error>;
const fetcher = (endpoint: string) => get(endpoint).then(response => response.data);
// Products
export interface Product {
_id: string;
name: string;
description: string;
price: number;
quantity: number;
specs: any;
createdAt: string;
updatedAt: string;
}
export const useProducts = (options = {}): Response<Product[]> => {
return useSWR('/products', fetcher, options);
};
export const useProduct = (_id: string): Response<Product> => {
const { data: preloadedProducts } = useProducts({ revalidateOnMount: false });
const result = useSWR(_id && `/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;
};
// Contractors
export interface Contractor {
_id: string;
name: string;
fullName: string;
vatId: string;
type: string;
debt: number;
}
export const useContractors = (options = {}): Response<Product[]> => {
return useSWR('/contractors', fetcher, options);
};
export const useContractor = (_id: string): Response<Product> => {
const { data: preloadedContractors } = useContractors({ revalidateOnMount: false });
const result = useSWR(_id && `/contractors/${_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 contractor = _.find(preloadedContractors, { _id });
return { ...result, data: contractor };
}
return result;
};
|