Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active January 25, 2023 04:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save intrnl/95d6a57a6a9af65b39398384331595ca to your computer and use it in GitHub Desktop.
Save intrnl/95d6a57a6a9af65b39398384331595ca to your computer and use it in GitHub Desktop.
useLazySWR hook for lazily querying
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