diff options
author | eug-vs <eug-vs@keemail.me> | 2021-03-25 23:09:49 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2021-03-25 23:09:49 +0300 |
commit | 062f10a25d43b875d187cf582b2ecf96d075ec26 (patch) | |
tree | c6b43379325ba22a051827e6a461a8f8fed98402 /src/hooks | |
parent | 77ac1549e2ab5ac68a1a7464ada9be7e2a2aad92 (diff) | |
download | commercel-ui-062f10a25d43b875d187cf582b2ecf96d075ec26.tar.gz |
refactor: move services to separate folder
Diffstat (limited to 'src/hooks')
-rw-r--r-- | src/hooks/useAPIClient.ts | 15 | ||||
-rw-r--r-- | src/hooks/useOptions.ts | 30 |
2 files changed, 6 insertions, 39 deletions
diff --git a/src/hooks/useAPIClient.ts b/src/hooks/useAPIClient.ts index 1fa9896..adb6d3f 100644 --- a/src/hooks/useAPIClient.ts +++ b/src/hooks/useAPIClient.ts @@ -1,13 +1,14 @@ import useSWR, { responseInterface } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; -import services from '../services'; type Response<T> = responseInterface<T, Error>; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); -const createServiceHooks = <Item = any>(service: string) => { +const hooks: any = {}; + +const registerServiceHooks = <Item = any>(service: string) => { const useList = (query = '', options = {}): Response<Item[]> => { return useSWR(`/${service}${query}`, fetcher, options); }; @@ -24,7 +25,7 @@ const createServiceHooks = <Item = any>(service: string) => { return result; }; - return { useItem, useList }; + hooks[service] = { useItem, useList }; }; // Products @@ -49,11 +50,6 @@ export interface Contractor { debt: number; } -const hooks = services.reduce((acc, { route }) => { - return _.set(acc, route, createServiceHooks(route)); -}, {}); - - hooks.account = { useList: () => { const { data: transfers } = useSWR('/transfers', fetcher); @@ -70,4 +66,5 @@ hooks.account = { }; -export default hooks as any; +export { registerServiceHooks }; +export default hooks; diff --git a/src/hooks/useOptions.ts b/src/hooks/useOptions.ts deleted file mode 100644 index 2a5aee6..0000000 --- a/src/hooks/useOptions.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { useEffect } from 'react'; -import _ from 'lodash'; -import { Option } from '../components/Select'; -import hooks from './useAPIClient'; - -// Load service entities and map them into select options -// setting the default value in formik -const useOptions = ( - service: string, - fields: string[], - values: Record<string, any>, - setFieldValue: (any) => void, - mapper = item => ({ key: item._id, label: item.name }), -): Option[] => { - const { data: items } = hooks[service].useList(); - - const options = items?.map(mapper); - - useEffect(() => { - // Initialize all empty fields - if (items?.length) fields.forEach(field => { - if (!_.get(values, field)) setFieldValue(field, items[0]._id); - }); - }, [items, values, setFieldValue]); - - return options; -}; - - -export default useOptions; |