diff options
author | eug-vs <eug-vs@keemail.me> | 2021-04-20 11:01:29 +0300 |
---|---|---|
committer | eug-vs <eug-vs@keemail.me> | 2021-04-20 11:01:42 +0300 |
commit | 8168218491ef454576079ad119e5deacf879d383 (patch) | |
tree | 9056f990d1bbc587ef490439395f9950b2445f44 | |
parent | 50f7d5d888b87f81fd399b677bfd542761091e94 (diff) | |
download | commercel-ui-8168218491ef454576079ad119e5deacf879d383.tar.gz |
refactor: strongly type API Client hooks
-rw-r--r-- | src/components/Select.tsx | 4 | ||||
-rw-r--r-- | src/hooks/useAPIClient.ts | 31 |
2 files changed, 13 insertions, 22 deletions
diff --git a/src/components/Select.tsx b/src/components/Select.tsx index e65f8c4..19f2aab 100644 --- a/src/components/Select.tsx +++ b/src/components/Select.tsx @@ -8,13 +8,13 @@ export interface Option { export interface Props extends React.SelectHTMLAttributes<HTMLSelectElement> { label?: string; - options: Option[]; + options?: Option[]; } const focusStyles = 'focus:outline-none focus:shadow focus:border-gray-400'; const baseStyles = 'p-2 border bg-white border-gray-300 rounded-sm'; -const SelectBase: React.FC<Props> = ({ label, options, ...props }) => { +const SelectBase: React.FC<Props> = ({ label, options = [], ...props }) => { return ( <div className="m-2 mb-4 flex flex-col"> <label htmlFor={props?.name} className="mb-1 text-sm text-gray-600">{label}</label> diff --git a/src/hooks/useAPIClient.ts b/src/hooks/useAPIClient.ts index 3035c51..fd3ee19 100644 --- a/src/hooks/useAPIClient.ts +++ b/src/hooks/useAPIClient.ts @@ -1,12 +1,20 @@ -import useSWR, { responseInterface } from 'swr'; +import useSWR, { SWRConfiguration, SWRResponse } from 'swr'; import _ from 'lodash'; import { get } from '../requests'; -type Response<T> = responseInterface<T, Error>; +type Response<T> = SWRResponse<T, Error>; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); -const hooks: any = {}; + +interface ServiceHooks<T = any> { + useList: (query?: string, options?: SWRConfiguration) => Response<T[]> + useItem: (id: string) => Response<T> +} + +type Hooks = Record<string, ServiceHooks>; + +const hooks: Hooks = {}; const registerServiceHooks = <Item = any>(service: string): void => { if (hooks[service]) return; @@ -30,22 +38,5 @@ const registerServiceHooks = <Item = any>(service: string): void => { hooks[service] = { useItem, useList }; }; -hooks.account = { - useList: () => { - const { data: transfers } = useSWR('/transfers', fetcher); - const dates = _.groupBy(transfers, 'date'); - const dataUnsorted = _.map(dates, (dateTransfers, date) => ({ - _id: dateTransfers[0]._id, // fake: sample id for unique key - date, - amount: _ - .sumBy(dateTransfers, transfer => transfer.amount * (transfer.operation === 'in' ? 1 : -1)) - .toFixed(1), - })); - const data = _.sortBy(dataUnsorted, 'date').reverse(); - return { data }; - }, -}; - - export { registerServiceHooks }; export default hooks; |