Skip to content

Call operations

@kubb/plugin-react-query turns each operation into a hook that wraps the client function from @kubb/plugin-axios or @kubb/plugin-fetch. Read operations become useFoo, write operations become useFoo mutations, and every hook is typed from the spec.

IMPORTANT

By default the plugin emits only the factory helpers (queryOptions, mutationOptions, queryKey, mutationKey). Set hooks: true in the plugin options to also generate the use* hooks shown below.

Queries

A query hook takes the operation's grouped request config (path, query, headers, whichever the operation declares) as its first argument and returns a TanStack UseQueryResult:

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

const { data, error, isLoading } = useGetPetById({ path: { petId: 1 } })

The second argument holds two option groups. query takes any TanStack Query option plus a client to target a specific QueryClient. client takes per-call request config for the underlying client, such as baseURL, headers, or timeout:

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

useGetPetById(
  { path: { petId: 1 } },
  {
    query: { staleTime: 60_000, enabled: petId != null },
    client: { headers: { 'X-Trace': 'abc' } },
  },
)

Factories

Every operation also exports a queryOptions factory and a queryKey helper, so you can prefetch, seed, or compose outside a hook. The key is [{ url, params }], built from the operation path and its path params:

typescript
import { useQueryClient } from '@tanstack/react-query'
import { getPetByIdQueryKey, getPetByIdQueryOptions } from './gen/hooks/useGetPetById'

const queryClient = useQueryClient()

await queryClient.prefetchQuery(getPetByIdQueryOptions({ path: { petId: 1 } }))
queryClient.invalidateQueries({ queryKey: getPetByIdQueryKey({ path: { petId: 1 } }) })

Mutations

A mutation hook takes only an options object. The grouped request config is the mutation variable, so you pass it to mutate or mutateAsync:

typescript
import { useQueryClient } from '@tanstack/react-query'
import { useDeletePet } from './gen/hooks/useDeletePet'

const queryClient = useQueryClient()

const { mutate } = useDeletePet({
  mutation: { onSuccess: () => queryClient.invalidateQueries() },
})

mutate({ path: { petId: 1 } })

A mutationOptions factory and mutationKey helper are exported next to the hook, mirroring the query factories.

Errors and transport

The generated hooks call the client operation with throwOnError: true, so failures surface through the query library's error state, typed from the spec's error responses. Transport concerns (base URL, authentication, interceptors, serialization, validation) live on the client plugin: see the plugin-fetch or plugin-axios guides.