useMutation()
非官方测试版翻译
本页面由 PageTurner AI 翻译(测试版)。未经项目官方认可。 发现错误? 报告问题 →
备注
@trpc/react-query 提供的钩子函数本质上是 @tanstack/react-query 的轻量封装。如需深入了解配置选项和使用模式,请参阅其官方文档中的变更操作章节。
功能实现与 react-query 的变更操作完全一致 - 参见其文档。
示例
Backend code
server/routers/_app.tstsximport { 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 querieslogin: t.procedure// using zod schema to validate and infer input values.input(z.object({name: z.string(),}),).mutation((opts) => {// Here some login stuff would happenreturn {user: {name: opts.input.name,role: 'ADMIN',},};}),});
server/routers/_app.tstsximport { 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 querieslogin: t.procedure// using zod schema to validate and infer input values.input(z.object({name: z.string(),}),).mutation((opts) => {// Here some login stuff would happenreturn {user: {name: opts.input.name,role: 'ADMIN',},};}),});
tsximport { 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>);}
tsximport { 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>);}