summaryrefslogtreecommitdiff
path: root/src/hooks
diff options
context:
space:
mode:
Diffstat (limited to 'src/hooks')
-rw-r--r--src/hooks/useAPIClient.ts31
1 files changed, 29 insertions, 2 deletions
diff --git a/src/hooks/useAPIClient.ts b/src/hooks/useAPIClient.ts
index f2f2782..eb427f1 100644
--- a/src/hooks/useAPIClient.ts
+++ b/src/hooks/useAPIClient.ts
@@ -4,6 +4,9 @@ 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;
@@ -15,8 +18,6 @@ export interface Product {
updatedAt: string;
}
-const fetcher = (endpoint: string) => get(endpoint).then(response => response.data);
-
export const useProducts = (options = {}): Response<Product[]> => {
return useSWR('/products', fetcher, options);
};
@@ -33,3 +34,29 @@ export const useProduct = (_id: string): Response<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;
+};