useMutation()
非公式ベータ版翻訳
このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →
@trpc/reactが提供するフックは、React Queryの薄いラッパーです。オプションや使用パターンに関する詳細は、Mutationsのドキュメントを参照してください。
react-queryのmutationsと同様に動作します - 詳細はドキュメントを参照。
例
Backend code
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { z } from 'zod';export const appRouter = trpc.router()// Create procedure at path 'login'// The syntax is identical to creating queries.mutation('login', {// using zod schema to validate and infer input valuesinput: z.object({name: z.string(),})async resolve({ input }) {// Here some login stuff would happenreturn {user: {name: input.name,role: 'ADMIN'},};},})
server/routers/_app.tstsximport * as trpc from '@trpc/server';import { z } from 'zod';export const appRouter = trpc.router()// Create procedure at path 'login'// The syntax is identical to creating queries.mutation('login', {// using zod schema to validate and infer input valuesinput: z.object({name: z.string(),})async resolve({ input }) {// Here some login stuff would happenreturn {user: {name: input.name,role: 'ADMIN'},};},})
tsximport { trpc } from '../utils/trpc';export function MyComponent() {// This can either be a tuple ['login'] or string 'login'const mutation = trpc.useMutation(['login']);const handleLogin = async () => {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>);}
tsximport { trpc } from '../utils/trpc';export function MyComponent() {// This can either be a tuple ['login'] or string 'login'const mutation = trpc.useMutation(['login']);const handleLogin = async () => {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>);}