Updated useData and util hooks

This commit is contained in:
Luis Alvarez 2021-05-25 14:19:52 -05:00
parent e7980e17f5
commit f8d69323bd
2 changed files with 10 additions and 9 deletions

View File

@ -2,10 +2,11 @@ import useSWR, { responseInterface } from 'swr'
import type { import type {
HookSWRInput, HookSWRInput,
HookFetchInput, HookFetchInput,
Fetcher,
SwrOptions,
HookFetcherOptions, HookFetcherOptions,
HookFetcherFn, HookFetcherFn,
Fetcher,
SwrOptions,
SWRHookSchemaBase,
} from './types' } from './types'
import defineProperty from './define-property' import defineProperty from './define-property'
import { CommerceError } from './errors' import { CommerceError } from './errors'
@ -14,15 +15,15 @@ export type ResponseState<Result> = responseInterface<Result, CommerceError> & {
isLoading: boolean isLoading: boolean
} }
export type UseData = <Data = any, FetchInput extends HookFetchInput = {}>( export type UseData = <H extends SWRHookSchemaBase>(
options: { options: {
fetchOptions: HookFetcherOptions fetchOptions: HookFetcherOptions
fetcher: HookFetcherFn<Data, FetchInput> fetcher: HookFetcherFn<H>
}, },
input: HookFetchInput | HookSWRInput, input: HookFetchInput | HookSWRInput,
fetcherFn: Fetcher, fetcherFn: Fetcher,
swrOptions?: SwrOptions<Data, FetchInput> swrOptions?: SwrOptions<H['data'], H['fetchInput']>
) => ResponseState<Data> ) => ResponseState<H['data']>
const useData: UseData = (options, input, fetcherFn, swrOptions) => { const useData: UseData = (options, input, fetcherFn, swrOptions) => {
const hookInput = Array.isArray(input) ? input : Object.entries(input) const hookInput = Array.isArray(input) ? input : Object.entries(input)

View File

@ -10,14 +10,14 @@ export function useFetcher() {
export function useHook< export function useHook<
P extends Provider, P extends Provider,
H extends MutationHook<any, any, any> | SWRHook<any, any, any> H extends MutationHook<any> | SWRHook<any>
>(fn: (provider: P) => H) { >(fn: (provider: P) => H) {
const { providerRef } = useCommerce<P>() const { providerRef } = useCommerce<P>()
const provider = providerRef.current const provider = providerRef.current
return fn(provider) return fn(provider)
} }
export function useSWRHook<H extends SWRHook<any, any, any>>( export function useSWRHook<H extends SWRHook<any>>(
hook: PickRequired<H, 'fetcher'> hook: PickRequired<H, 'fetcher'>
) { ) {
const fetcher = useFetcher() const fetcher = useFetcher()
@ -30,7 +30,7 @@ export function useSWRHook<H extends SWRHook<any, any, any>>(
}) })
} }
export function useMutationHook<H extends MutationHook<any, any, any>>( export function useMutationHook<H extends MutationHook<any>>(
hook: PickRequired<H, 'fetcher'> hook: PickRequired<H, 'fetcher'>
) { ) {
const fetcher = useFetcher() const fetcher = useFetcher()