Skip to content
SWR logo

SWR

Officialv5.10.0

@kubb/plugin-swr

kubb add plugin-swr

Call operations

Use the generated useSWR and useSWRMutation hooks, and skip or freeze a request with the Kubb options.

What each plugin generates

Each hook and its helpers live in a file named after the hook, such as src/gen/hooks/useGetPetById.ts.

OperationExports
Query (GET, QUERY)getPetByIdQueryKey, getPetByIdQueryOptions, useGetPetById
Mutation (POST, PUT, PATCH, DELETE)updatePetMutationKey, useUpdatePet
Infinite or suspenseNot generated
Server-Sent Events or JSON LinesNothing. Call the client function directly.

Call a hook

The examples set integerType: 'number' on the adapter so petId is a number. Path keys keep their spec names unless you set pathParamsCasing.

The first argument takes the request groups: path, query, headers. The second takes SWR options (SWRConfiguration) in query, request config such as baseURL in client, and the Kubb options shouldFetch and immutable.

import { useGetPetById } from './gen/hooks/useGetPetById'

const { data, error, isLoading } = useGetPetById(
  { path: { petId: 1 } },
  { query: { refreshInterval: 30_000 }, client: { baseURL: 'https://api.example.com/v1' } },
)

Pass a queryKey helper to SWR's mutate to update or revalidate that entry. SWR keys shows the default keys. To change them, set queryKey and mutationKey.

Skip requests until ready

shouldFetch: false gives SWR a null key, so the request waits until you pass true. On a mutation hook, shouldFetch: false makes trigger throw a missing-key error.

import { useGetPetById } from './gen/hooks/useGetPetById'

export function useSelectedPet(petId: number | undefined) {
  return useGetPetById({ path: { petId: petId ?? 0 } }, { shouldFetch: petId != null })
}

Fetch immutable data

immutable: true on a query hook sets revalidateIfStale, revalidateOnFocus, and revalidateOnReconnect to false. Options in query still win.

const { data } = useGetPetById({ path: { petId: 1 } }, { immutable: true })

Handle errors

Each hook calls the client with throwOnError: true, so a failed request sets SWR's error, typed from the spec's error responses.

Next, set the base URL, auth, and interceptors on your client plugin: plugin-fetch, plugin-axios, plugin-ky, or your own module with plugin-client.