Await tRPC Mutation response

Can you await a trpc mutation response? For instance onClick fire a async function handler and await the trpc.user.create.mutation()
3 Replies
mrnicericee
mrnicericee2y ago
Mutations | TanStack Query Docs
Unlike queries, mutations are typically used to create/update/delete data or perform server side-effects. For this purpose, TanStack Query exports a useMutation hook. Here's an example of a mutation that adds a new todo to the server:
mrnicericee
mrnicericee2y ago
ah dang wasn't done typing haha
// pulled from https://trpc.io/docs/useMutation
import { trpc } from '../utils/trpc';
export function MyComponent() {
// This can either be a tuple ['login'] or string 'login'
const mutation = trpc.login.useMutation();
const handleLogin = async () => {
const name = 'John Doe';
await mutation.mutateAsync({ name }); // change mutate to mutateAsync
// other things you want to do
};
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>
);
}
// pulled from https://trpc.io/docs/useMutation
import { trpc } from '../utils/trpc';
export function MyComponent() {
// This can either be a tuple ['login'] or string 'login'
const mutation = trpc.login.useMutation();
const handleLogin = async () => {
const name = 'John Doe';
await mutation.mutateAsync({ name }); // change mutate to mutateAsync
// other things you want to do
};
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>
);
}
codefork
codefork2y ago
@MrNiceRicee Perfect thanks mate!
Want results from more Discord servers?
Add your server