Skip to content

Skip a request until ready

@kubb/plugin-swr generates a useFoo hook whose second argument accepts a Kubb-specific shouldFetch switch. Set it to false to make the key null, so SWR skips the request until the value the hook depends on is ready.

kubb.config.ts
typescript
import { defineConfig } from 'kubb/config'
import { pluginTs } from '@kubb/plugin-ts'
import { pluginFetch } from '@kubb/plugin-fetch'
import { pluginSwr } from '@kubb/plugin-swr'

export default defineConfig({
  input: './petStore.yaml',
  output: { path: './src/gen', clean: true },
  plugins: [pluginTs(), pluginFetch(), pluginSwr({ output: { path: 'hooks', mode: 'directory' } })],
})
typescript
import { useGetPetById } from './gen/hooks/useGetPetById'

const petId: number | undefined = undefined

const { data } = useGetPetById(
  { path: { petId: petId ?? 0 } },
  { shouldFetch: petId != null },
)

Output example

src/gen/hooks/useGetPetById.ts
typescript
export function useGetPetById({ path }: GetPetByIdOptions, options: {
  query?: SWRConfiguration<GetPetByIdResponse, ResponseErrorConfig<GetPetByIdStatus400 | GetPetByIdStatus404>>,
  client?: Partial<Omit<RequestConfig, 'path' | 'query' | 'body' | 'headers' | 'url'>>,
  shouldFetch?: boolean,
  immutable?: boolean
} = {}) {
  const { query: queryOptions, client: config = {}, shouldFetch = true, immutable } = options ?? {}

  const queryKey = getPetByIdQueryKey({ path })

  return useSWR<GetPetByIdResponse, ResponseErrorConfig<GetPetByIdStatus400 | GetPetByIdStatus404>, GetPetByIdQueryKey | null>(
   shouldFetch ? queryKey : null,
   {
     ...getPetByIdQueryOptions({ path }, config),
     ...queryOptions,
   }
  )
}
usage.ts
typescript
import { useGetPetById } from './gen/hooks/useGetPetById'

const petId: number | undefined = undefined

// shouldFetch: false turns the SWR key into null, so the request is skipped
const { data } = useGetPetById(
  { path: { petId: petId ?? 0 } },
  { shouldFetch: petId != null },
)