Skip to content
Official v5.0.0 MIT kubb >=5.0.0 node >=22

@kubb/plugin-swr

Generates typed SWR hooks from your OpenAPI spec, so data fetching stays in sync with the API.

swrreacthooksdata-fetchingcodegenopenapi
Downloads
39.2k / mo
Stars
5
Bundle size
309.8 kB
Updated
2d ago

@kubb/plugin-swr

@kubb/plugin-swr turns each OpenAPI operation into an SWR hook. Read operations become useSWR hooks. Write operations become useSWRMutation hooks. Every hook is typed: keys, input variables, response data, and error shape all come from the spec.

The hooks call an HTTP client, so add @kubb/plugin-ts for the types and either @kubb/plugin-axios or @kubb/plugin-fetch for the client. Generation errors out when no client plugin is registered.

Query hooks take the grouped request config ({ path, query, headers }, camelCase property names) as their first argument. Mutation hooks take only an options object, and you pass the grouped config through trigger(...) instead. The request still sends the original parameter names from the spec, and Kubb writes that mapping for you.

Installation

shell
bun add -d @kubb/plugin-swr
shell
pnpm add -D @kubb/plugin-swr
shell
npm install --save-dev @kubb/plugin-swr
shell
yarn add -D @kubb/plugin-swr

Dependencies

This plugin needs these plugins in your config:

IMPORTANT

The generated hooks need SWR v2 or higher.

For runtime validation, set validator on the client plugin. The generated operations carry the validation, so the hooks get it for free.

Example

typescript
import { 
defineConfig
} from 'kubb'
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' },
plugins
: [
pluginTs
(),
pluginFetch
(),
pluginSwr
({
output
: {
path
: './hooks',
mode
: 'directory' },
group
: {
type
: 'tag',
name
: ({
group
}) => `${
group
}Hooks` },
client
: 'fetch',
query
: {
methods
: ['GET'],
importPath
: 'swr' },
mutation
: {
methods
: ['POST', 'PUT', 'PATCH', 'DELETE'] },
}), ], })

See also