본문으로 건너뛰기
버전: 11.x

useMutation()

노트

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

예시

백엔드 코드
server/routers/_app.ts
tsx
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 queries
login: t.procedure
// using zod schema to validate and infer input values
.input(
z.object({
name: z.string(),
}),
)
.mutation((opts) => {
// Here some login stuff would happen
return {
user: {
name: opts.input.name,
role: 'ADMIN' as const,
},
};
}),
});
 
export type AppRouter = typeof appRouter;
server/routers/_app.ts
tsx
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 queries
login: t.procedure
// using zod schema to validate and infer input values
.input(
z.object({
name: z.string(),
}),
)
.mutation((opts) => {
// Here some login stuff would happen
return {
user: {
name: opts.input.name,
role: 'ADMIN' as const,
},
};
}),
});
 
export type AppRouter = typeof appRouter;
tsx
import { trpc } from '../utils/trpc';
 
export function MyComponent() {
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.isPending}>
Login
</button>
 
{mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
</div>
);
}
tsx
import { trpc } from '../utils/trpc';
 
export function MyComponent() {
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.isPending}>
Login
</button>
 
{mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
</div>
);
}