Aller au contenu principal
Version : 9.x

useMutation()

Traduction Bêta Non Officielle

Cette page a été traduite par PageTurner AI (bêta). Non approuvée officiellement par le projet. Vous avez trouvé une erreur ? Signaler un problème →

Les hooks fournis par @trpc/react sont une fine surcouche autour de React Query. Pour des informations détaillées sur les options et les modèles d'utilisation, consultez leur documentation sur les Mutations.

Fonctionne comme les mutations de react-query - voir leur documentation.

Exemple

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>
);
}