Is there a typescript example of useSWR #939
Replies: 4 comments 9 replies
-
i kinda do not understand where your problem is, when you hover over your imported useSwr Function, you see how you can give types for data and error? like this?
|
Beta Was this translation helpful? Give feedback.
-
This is a resume based on the answers (Thank you so much by the way). The export default async function fetcher<JSON = any>(
input: RequestInfo,
init?: RequestInit
): Promise<JSON> {
const res = await fetch(input, init);
return res.json();
} The use data function as follows: export function MyComponent() {
const { data, error } = useSWR<BuildingObj, Error>('/api/v3/public/building', fetcher);
// Do your business here
}
I guess this is the most basic way but it works =') |
Beta Was this translation helpful? Give feedback.
-
export const httpGet = async <T>(input: RequestInfo | URL): Promise<T> => {
const accessToken = getAccessToken();
if (!accessToken) {
throw Error("accessToken required")
}
const init: RequestInit = {
method: "GET",
headers: {
"Content-Type": "application/json",
"Accept": "application/json",
"Authorization": `Bearer ${accessToken}`
}
}
const res = await fetch(input, init);
return await res.json();
} it works. |
Beta Was this translation helpful? Give feedback.
-
Here is how I usually do it in a Next.js project's import type { AppProps } from "next/app";
async function fetcher(...args: Parameters<typeof fetch>) {
return (await fetch(...args)).json();
}
export default function App({ Component, pageProps }: AppProps) {
return (
<SWRConfig value={{ fetcher }}>
...
</SWRConfig>
);
} |
Beta Was this translation helpful? Give feedback.
-
Is there a typescript example of useSWR with proper types for data and error? I couldn't find one.
Beta Was this translation helpful? Give feedback.
All reactions