Skip to content

Latest commit

 

History

History
88 lines (67 loc) · 2.93 KB

File metadata and controls

88 lines (67 loc) · 2.93 KB
title mutationOptions

{{ $frontmatter.title }}

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.

Examples

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.

:::

API

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 UseMutationOptions for React Query.
    • You can set callbacks (onSuccess, onSettled, …), retry behaviour, and every option except mutationKey and mutationFn (those are provided for you).

Returns

  • Mutation Options
    • mutationKey is [method, path].
    • mutationFn is a strongly typed fetcher that calls openapi-fetch with your init payload.
    • data and error types match the OpenAPI schema, so variables inside callbacks are typed as the request shape.