Last active
January 25, 2023 04:41
-
-
Save intrnl/95d6a57a6a9af65b39398384331595ca to your computer and use it in GitHub Desktop.
useLazySWR hook for lazily querying
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from 'react' | |
import useSWR, { type Fetcher, type Key, type SWRConfiguration, type SWRResponse } from 'swr' | |
type ArgumentsTuple = [any, ...unknown[]] | readonly [any, ...unknown[]] | |
type StrictTupleKey = ArgumentsTuple | null | undefined | false | |
type StrictKey = StrictTupleKey | (() => StrictTupleKey) | |
type SetKey<T> = React.Dispatch<React.SetStateAction<T>> | |
export function useLazySWR< | |
D = any, | |
E = any, | |
K extends Key = StrictKey, | |
O extends SWRConfiguration<D, E, Fetcher<D, K>> | undefined = | |
| SWRConfiguration<D, E, Fetcher<D, K>> | |
| undefined | |
>( | |
fetcher: Fetcher<D, K> | null, | |
config?: O | |
): [SetKey<K | false>, SWRResponse<D, E>] { | |
const [key, setKey] = React.useState<false | K>(false) | |
const result = useSWR<D, E, K>(key as K, fetcher, config) | |
return [setKey, result] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment