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