From 8168218491ef454576079ad119e5deacf879d383 Mon Sep 17 00:00:00 2001 From: eug-vs Date: Tue, 20 Apr 2021 11:01:29 +0300 Subject: refactor: strongly type API Client hooks --- src/components/Select.tsx | 4 ++-- 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 { 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 = ({ label, options, ...props }) => { +const SelectBase: React.FC = ({ label, options = [], ...props }) => { return (
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 = responseInterface; +type Response = SWRResponse; const fetcher = (endpoint: string) => get(endpoint).then(response => response.data); -const hooks: any = {}; + +interface ServiceHooks { + useList: (query?: string, options?: SWRConfiguration) => Response + useItem: (id: string) => Response +} + +type Hooks = Record; + +const hooks: Hooks = {}; const registerServiceHooks = (service: string): void => { if (hooks[service]) return; @@ -30,22 +38,5 @@ const registerServiceHooks = (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; -- cgit v1.2.3