UNPKG

swr-openapi

Version:
89 lines (82 loc) 2.66 kB
import useSWRImmutable from 'swr/immutable'; import { useDebugValue, useMemo, useCallback } from 'react'; import useSWRInfinite from 'swr/infinite'; import useSWR, { useSWRConfig } from 'swr'; function configureBaseQueryHook(useHook) { return function createQueryBaseHook(client, prefix) { return function useQuery(path, ...[init, config]) { useDebugValue(`${prefix} - ${path}`); const key = useMemo(() => init !== null ? [prefix, path, init] : null, [prefix, path, init]); const fetcher = useCallback( async ([_, path2, init2]) => { const res = await client.GET(path2, init2); if (res.error) { throw res.error; } return res.data; }, [client] ); return useHook(key, fetcher, config); }; }; } const createImmutableHook = configureBaseQueryHook(useSWRImmutable); function createInfiniteHook(client, prefix) { return function useInfinite(path, getInit, config) { useDebugValue(`${prefix} - ${path}`); const fetcher = useCallback( async ([_, path2, init]) => { const res = await client.GET(path2, init); if (res.error) { throw res.error; } return res.data; }, [client] ); const getKey = (index, previousPageData) => { const init = getInit(index, previousPageData); if (init === null) { return null; } const key = [prefix, path, init]; return key; }; return useSWRInfinite(getKey, fetcher, config); }; } function createMutateHook(client, prefix, compare) { return function useMutate() { const { mutate: swrMutate } = useSWRConfig(); useDebugValue(prefix); return useCallback( function mutate([path, init], data, opts) { return swrMutate( (key) => { if ( // Must be array !Array.isArray(key) || // Must have 2 or 3 elements (prefix, path, optional init) ![2, 3].includes(key.length) ) { return false; } const [keyPrefix, keyPath, keyOptions] = key; return ( // Matching prefix keyPrefix === prefix && // Matching path keyPath === path && // Matching options (init ? compare(keyOptions, init) : true) ); }, data, opts ); }, [swrMutate, prefix, compare] ); }; } const createQueryHook = configureBaseQueryHook(useSWR); export { createImmutableHook, createInfiniteHook, createMutateHook, createQueryHook }; //# sourceMappingURL=index.mjs.map