useMutation()
비공식 베타 번역
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
참고
@trpc/react-query가 제공하는 훅은 @tanstack/react-query를 얇게 감싼 래퍼(wrapper)입니다. 옵션과 사용 패턴에 대한 자세한 내용은 mutations 문서를 참조하세요.
react-query의 mutations과 동일하게 동작합니다 - 공식 문서 참조.
예시
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() {// 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>);}
tsximport { 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>);}