---
url: >-
  https://openapi-typesafe.github.io/openapi-typesafe/react-query/use-mutation.md
description: Typed useMutation for OpenAPI endpoints
---

# {{ $frontmatter.title }}

The `useMutation` method allows you to use the original [useMutation](https://tanstack.com/query/latest/docs/framework/react/guides/mutations).

* The result is the same as the original function.
* The `mutationKey` is `[method, path]`.
* `data` and `error` are fully typed.

::: tip
You can find more information about `useMutation` on the [@tanstack/react-query documentation](https://tanstack.com/query/latest/docs/framework/react/guides/mutations).
:::

## Example

::: code-group

```tsx [src/app.tsx]
import { $api } from "./api";

export const App = () => {
  const { mutate } = $api.useMutation("patch", "/users");

  return (
    <button onClick={() => mutate({ body: { firstname: "John" } })}>
      Update
    </button>
  );
};
```

```ts [src/api.ts]
import createFetchClient from "openapi-typesafe-fetch";
import createClient from "openapi-typesafe-react-query";
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typesafe

const fetchClient = createFetchClient<paths>({
  baseUrl: "https://myapi.dev/v1/",
});
export const $api = createClient(fetchClient);
```

:::

## Api

```tsx
const mutation = $api.useMutation(method, path, mutationOptions, queryClient);
```

**Arguments**

* `method` **(required)**
  * The HTTP method to use for the request.
  * The method is used as key. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information.
* `path` **(required)**
  * The pathname to use for the request.
  * Must be an available path for the given method in your schema.
  * The pathname is used as key. See [Query Keys](https://tanstack.com/query/latest/docs/framework/react/guides/query-keys) for more information.
* `mutationOptions`
  * The original `useMutation` options.
  * [See more information](https://tanstack.com/query/latest/docs/framework/react/reference/useMutation)
* `queryClient`
  * The original `queryClient` option.
  * [See more information](https://tanstack.com/query/latest/docs/framework/react/reference/useMutation)
