useMutation()
備註
@trpc/react-query
提供的掛勾是 @tanstack/react-query 的一層薄封裝。有關選項和使用模式的詳細資訊,請參閱其關於 變異 的文件。
運作方式類似於 react-query 的變異 - 參閱其文件。
範例
後端程式碼
server/routers/_app.tstsx
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 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.tstsx
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 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',},};}),});
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>);}