跳至主要内容
版本:11.x

useMutation()

注意

@trpc/react-query 提供的钩子是围绕 @tanstack/react-query 的一个薄包装器。有关选项和使用模式的深入信息,请参阅其文档 mutations

与 react-query 的 mutations 类似 - 查看其文档

示例

后端代码
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() {
// This can either be a tuple ['login'] or string 'login'
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.isLoading}>
Login
</button>
{mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
</div>
);
}
tsx
import { trpc } from '../utils/trpc';
export function MyComponent() {
// This can either be a tuple ['login'] or string 'login'
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.isLoading}>
Login
</button>
{mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
</div>
);
}