Last active
February 25, 2021 12:38
-
-
Save dpacmittal/60e8fa5f6e33a6f1e2edb815a749e96b to your computer and use it in GitHub Desktop.
React hook to send requests lazily with SWR
This file contains hidden or 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 { useState } from "react"; | |
import useSWR, { ConfigInterface, keyInterface } from "swr"; | |
import { fetcherFn } from "swr/dist/types"; | |
export const useLazySWR = <T, U>( | |
key: keyInterface, | |
fn?: fetcherFn<T>, | |
config?: ConfigInterface<T, U> | |
) => { | |
const [shouldFetch, setShouldFetch] = useState(false); | |
const ret = useSWR<T, U>(shouldFetch ? key : null, fn, config); | |
const execute = () => { | |
setShouldFetch(true); | |
}; | |
return { | |
...ret, | |
execute, | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment