Skip to content

Instantly share code, notes, and snippets.

@dpacmittal
Last active February 25, 2021 12:38
Show Gist options
  • Save dpacmittal/60e8fa5f6e33a6f1e2edb815a749e96b to your computer and use it in GitHub Desktop.
Save dpacmittal/60e8fa5f6e33a6f1e2edb815a749e96b to your computer and use it in GitHub Desktop.
React hook to send requests lazily with SWR
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