useMutation()

The hooks provided by @trpc/react are a thin wrapper around React Query. For in-depth information about options and usage patterns, refer to their docs on Mutations.

Works like react-query’s mutations - see their docs.

Example

Backend code

server/routers/_app.ts

  1. import * as trpc from '@trpc/server';
  2. import { z } from 'zod';
  3. export const appRouter = trpc.router()
  4. // Create procedure at path 'login'
  5. // The syntax is identical to creating queries
  6. .mutation('login', {
  7. // using zod schema to validate and infer input values
  8. input: z
  9. .object({
  10. name: z.string(),
  11. })
  12. async resolve({ input }) {
  13. // Here some login stuff would happen
  14. return {
  15. user: {
  16. name: input.name,
  17. role: 'ADMIN'
  18. },
  19. };
  20. },
  21. })
  1. import { trpc } from '../utils/trpc';
  2. export function MyComponent() {
  3. // This can either be a tuple ['login'] or string 'login'
  4. const mutation = trpc.useMutation(['login']);
  5. const handleLogin = async () => {
  6. const name = 'John Doe';
  7. mutation.mutate({ name });
  8. };
  9. return (
  10. <div>
  11. <h1>Login Form</h1>
  12. <button onClick={handleLogin} disabled={mutation.isLoading}>Login</button>
  13. {mutation.error && <p>Something went wrong! {mutation.error.message}</p>}
  14. </div>
  15. );
  16. }