Hoppa till huvudinnehållet
Version: 11.x

useMutation()

Inofficiell Beta-översättning

Denna sida har översatts av PageTurner AI (beta). Inte officiellt godkänd av projektet. Hittade du ett fel? Rapportera problem →

notering

Hookarna som tillhandahålls av @trpc/react-query är ett tunt lager ovanpå @tanstack/react-query. För djupgående information om alternativ och användningsmönster, se deras dokumentation om mutations.

Fungerar som mutations i react-query – se deras dokumentation.

Exempel

Backend code
server/routers/_app.ts
tsx
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
export const t = initTRPC.create();
export const appRouter = t.router({
// Create procedure at path 'login'
// The syntax is identical to creating queries
login: t.procedure
// using zod schema to validate and infer input values
.input(
z.object({
name: z.string(),
}),
)
.mutation((opts) => {
// Here some login stuff would happen
return {
user: {
name: opts.input.name,
role: 'ADMIN',
},
};
}),
});
server/routers/_app.ts
tsx
import { initTRPC } from '@trpc/server';
import { z } from 'zod';
export const t = initTRPC.create();
export const appRouter = t.router({
// Create procedure at path 'login'
// The syntax is identical to creating queries
login: t.procedure
// using zod schema to validate and infer input values
.input(
z.object({
name: z.string(),
}),
)
.mutation((opts) => {
// Here some login stuff would happen
return {
user: {
name: opts.input.name,
role: 'ADMIN',
},
};
}),
});
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const mutation = trpc.login.useMutation();
const handleLogin = () => {
const name = 'John Doe';
mutation.mutate({ name });
};
return (
<div>
<h1>Login Form</h1>
<button onClick={handleLogin} disabled={mutation.isPending}>
Login
</button>
{mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
</div>
);
}
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
const mutation = trpc.login.useMutation();
const handleLogin = () => {
const name = 'John Doe';
mutation.mutate({ name });
};
return (
<div>
<h1>Login Form</h1>
<button onClick={handleLogin} disabled={mutation.isPending}>
Login
</button>
{mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
</div>
);
}