SWR
Generate type-safe SWR hooks from OpenAPI
Generate fully typed SWR hooks from your OpenAPI specification.
Configuration
Set the client option to swr:
import { defineConfig } from 'orval';
export default defineConfig({
petstore: {
output: {
mode: 'tags-split',
target: 'src/api/petstore.ts',
schemas: 'src/api/model',
client: 'swr',
mock: true,
},
input: {
target: './petstore.yaml',
},
},
});Generated Output
Orval generates one custom hook per path in your OpenAPI specification. For example, this specification generates:
export const showPetById = (
petId: string,
options?: AxiosRequestConfig,
): Promise<AxiosResponse<Pet>> => {
return axios.get(`/pets/${petId}`, options);
};
export const getShowPetByIdKey = (petId: string) => [`/pets/${petId}`];
export const useShowPetById = <TError = Error>(
petId: string,
options?: {
swr?: SWRConfiguration<AsyncReturnType<typeof showPetById>, TError> & {
swrKey?: Key;
enabled?: boolean;
};
axios?: AxiosRequestConfig;
},
) => {
const { swr: swrOptions, axios: axiosOptions } = options ?? {};
const isEnabled =
swrOptions?.enabled !== false &&
petId !== null &&
petId !== undefined;
const swrKey =
swrOptions?.swrKey ?? (() => (isEnabled ? getShowPetByIdKey(petId) : null));
const swrFn = () => showPetById(petId, axiosOptions);
const query = useSwr<AsyncReturnType<typeof swrFn>, TError>(
swrKey,
swrFn,
swrOptions,
);
return {
swrKey,
...query,
};
};Usage
import { useShowPetById } from './api/petstore';
function PetDetails({ petId }: { petId: string }) {
const { data, error, isLoading } = useShowPetById(petId);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return (
<div>
<h1>{data?.name}</h1>
<p>ID: {data?.id}</p>
</div>
);
}Conditional Fetching
Disable the hook conditionally:
const { data } = useShowPetById(petId, {
swr: {
enabled: petId !== null && petId !== undefined, // Only fetch when petId is defined
},
});Full Example
See the complete SWR example on GitHub.