Skip to main content

Mutations

The hooks provided by @trpc/react are a thin wrapper around React Query. For in-depth information about options and usage patterns, refer to their docs on Mutations.

Works like react-query's mutations - see their docs.

If you have an optional input argument you'll have to pass null or undefined as the input - see this discussion for more details.

Example#

Backend code
import * as trpc from '@trpc/server';
import { z } from 'zod';
trpc.router()
// Create procedure at path 'login'
// The syntax is identical to creating queries
.mutation('login', {
// using zod schema to validate and infer input values
input: z
.object({
name: z.string(),
})
async resolve({ input }) {
// Here some login stuff would happen
return {
user: {
name: input.name,
role: 'ADMIN'
},
};
},
})
import { trpc } from '../utils/trpc';
export function MyComponent() {
// Note! This is not a tuple ['login', ...] but a string 'login'
const login = trpc.useMutation('login');
const handleLogin = async () => {
const name = 'John Doe';
await login.mutateAsync({ name });
};
return (
<div>
<h1>Login Form</h1>
<button onClick={handleLogin}>Login</button>
</div>
);
}