useMutation()
note
The hooks provided by @trpc/react-query are a thin wrapper around @tanstack/react-query. For in-depth information about options and usage patterns, refer to their docs on mutations.
Example
Backend code
server/routers/_app.tstsximport {initTRPC } from '@trpc/server';import {z } from 'zod';export constt =initTRPC .create ();export constappRouter =t .router ({// Create procedure at path 'login'// The syntax is identical to creating querieslogin :t .procedure // using zod schema to validate and infer input values.input (z .object ({name :z .string (),}),).mutation ((opts ) => {// Here some login stuff would happenreturn {user : {name :opts .input .name ,role : 'ADMIN' asconst ,},};}),});export typeAppRouter = typeofappRouter ;
server/routers/_app.tstsximport {initTRPC } from '@trpc/server';import {z } from 'zod';export constt =initTRPC .create ();export constappRouter =t .router ({// Create procedure at path 'login'// The syntax is identical to creating querieslogin :t .procedure // using zod schema to validate and infer input values.input (z .object ({name :z .string (),}),).mutation ((opts ) => {// Here some login stuff would happenreturn {user : {name :opts .input .name ,role : 'ADMIN' asconst ,},};}),});export typeAppRouter = typeofappRouter ;
tsximport {trpc } from '../utils/trpc';export functionMyComponent () {constmutation =trpc .login .useMutation ();consthandleLogin = () => {constname = '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 >);}
tsximport {trpc } from '../utils/trpc';export functionMyComponent () {constmutation =trpc .login .useMutation ();consthandleLogin = () => {constname = '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 >);}