Created
March 22, 2025 21:32
-
-
Save Profesor08/f9316fe011b8e7b8c397cbe62b588044 to your computer and use it in GitHub Desktop.
useSWR wrapper with improved types
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 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