useQuery
This hook is a typed wrapper over useSWR.
ts
import createClient from "openapi-fetch";
import { createQueryHook } from "swr-openapi";
import type { paths } from "./my-schema";
const client = createClient<paths>(/* ... */);
const useQuery = createQueryHook(client, "my-api");
const { data, error, isLoading, isValidating, mutate } = useQuery(
path,
init,
config,
);API
Parameters
path: Any endpoint that supportsGETrequests.init: (sometimes optional)- Fetch options for the chosen endpoint.
nullto skip the request (see SWR Conditional Fetching).
config: (optional) SWR options.
Returns
- An SWR response.
How It Works
useQuery is a very thin wrapper over useSWR. Most of the code involves TypeScript generics that are transpiled away.
The prefix supplied in createQueryHook is joined with path and init to form the key passed to SWR.
prefixis only used to help ensure uniqueness for SWR's cache, in the case that two or more API clients share an identical path (e.g./api/health). It is not included in actualGETrequests.
Then, GET is invoked with path and init. Short and sweet.
ts
function useQuery(path, ...[init, config]) {
return useSWR(
init !== null ? [prefix, path, init] : null,
async ([_prefix, path, init]) => {
const res = await client.GET(path, init);
if (res.error) {
throw res.error;
}
return res.data;
},
config,
);
}