| title | mutationOptions |
|---|
The mutationOptions method lets you build type-safe Mutation Options that plug directly into React Query APIs.
Use it whenever you want to call $api mutations but still provide your own useMutation (or other mutation consumer) configuration. The helper wires up the correct mutationKey, generates a fetcher that calls your OpenAPI endpoint, and preserves the inferred data and error types.
Rewriting the useMutation example to use mutationOptions.
::: code-group
import { useMutation } from '@tanstack/react-query';
import { $api } from './api';
export const App = () => {
const updateUser = useMutation(
$api.mutationOptions('patch', '/users/{user_id}', {
onSuccess: (data, variables) => {
console.log('Updated', variables.params?.path?.user_id, data.firstname);
},
})
);
return (
<button
onClick={() =>
updateUser.mutate({
params: { path: { user_id: 5 } },
body: { firstname: 'John' },
})
}
>
Update
</button>
);
};import createFetchClient from 'openapi-fetch';
import createClient from 'openapi-react-query';
import type { paths } from './my-openapi-3-schema'; // generated by openapi-typescript
const fetchClient = createFetchClient<paths>({
baseUrl: 'https://myapi.dev/v1/',
});
export const $api = createClient(fetchClient);:::
::: info Good to Know
$api.useMutation uses the same fetcher and key contract as mutationOptions. Reach for mutationOptions when you need to share mutation configuration across components or call React Query utilities such as queryClient.mutationDefaults.
:::
const options = $api.mutationOptions(method, path, mutationOptions);Arguments
method(required)- HTTP method of the OpenAPI operation.
- Also used as the first element of the mutation key.
path(required)- Pathname of the OpenAPI operation.
- Must be valid for the given method in your generated schema.
- Used as the second element of the mutation key.
mutationOptions- Optional
UseMutationOptionsfor React Query. - You can set callbacks (
onSuccess,onSettled, …), retry behaviour, and every option exceptmutationKeyandmutationFn(those are provided for you).
- Optional
Returns
- Mutation Options
mutationKeyis[method, path].mutationFnis a strongly typed fetcher that callsopenapi-fetchwith yourinitpayload.dataanderrortypes match the OpenAPI schema, sovariablesinside callbacks are typed as the request shape.