본문 바로가기
버전: 9.x

useMutation()

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

@trpc/react에서 제공하는 훅은 React Query를 간단히 감싼 래퍼입니다. 옵션과 사용 패턴에 대한 자세한 내용은 뮤테이션 문서를 참조하세요.

react-query의 뮤테이션과 동일하게 동작합니다 - 공식 문서 참조.

예시

Backend code
server/routers/_app.ts
tsx
import * 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 values
input: z
.object({
name: z.string(),
})
async resolve({ input }) {
// Here some login stuff would happen
return {
user: {
name: input.name,
role: 'ADMIN'
},
};
},
})
server/routers/_app.ts
tsx
import * 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 values
input: z
.object({
name: z.string(),
})
async resolve({ input }) {
// Here some login stuff would happen
return {
user: {
name: 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.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>
);
}
tsx
import { 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>
);
}