Skip to content

Instantly share code, notes, and snippets.

@Profesor08
Created March 22, 2025 21:32
Show Gist options
  • Save Profesor08/f9316fe011b8e7b8c397cbe62b588044 to your computer and use it in GitHub Desktop.
Save Profesor08/f9316fe011b8e7b8c397cbe62b588044 to your computer and use it in GitHub Desktop.
useSWR wrapper with improved types
import useSWR from "swr";
type Fetcher<FetchData, FetchKey extends Key> = (
key: FetchKey
) => FetcherResponse<FetchData>;
type FetcherResponse<FetchData = unknown> = FetchData | Promise<FetchData>;
type KeyValue =
| string
| false
| Record<string | number, unknown>
| null
| undefined
| KeyValue[];
type Key = KeyValue | [KeyValue, ...KeyValue[]];
export const useFetch = <
FetchData = unknown,
FetchError extends Error = Error,
FetchKey extends Key = Key
>(
key: FetchKey | (() => FetchKey),
fetcher: Fetcher<FetchData, FetchKey>
) => {
return useSWR<FetchData, FetchError, FetchKey | (() => FetchKey)>(key, () => {
return fetcher(typeof key === "function" ? key() : key);
});
};
const useTest = () => {
const { data } = useFetch("/api/post", (key) => {
return {
prop: 123,
};
});
useFetch(false, (key) => {});
useFetch(null, (key) => {});
useFetch(undefined, (key) => {});
useFetch(["hello", "world"], ([hello, world]) => {
console.log(hello, world);
});
useFetch(
{
hello: "world",
},
(key) => {}
);
useFetch(["/api/post", false, null, undefined], (key) => {});
useFetch(
["/api/post", false, null, undefined, ["hello", "world"]],
(key) => {}
);
useFetch(
() => "/api/post",
(key) => {}
);
useFetch(
() => "/api/post",
(key) => {}
);
useFetch(
() => "/api/post",
async (key) => {}
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment