The previous example shows how to create a query, which means "getting data" from the API. If you want to perform a mutation (e.g. create, update, delete), you create a mutation endpoint instead.
This looks very similar to the query:
import { z } from "zod" ;
import { publicProcedure } from "../../trpc" ;
import { db, PostSchema } from "database" ;
export const createPost = publicProcedure
. input (
z. object ({
title: z. string (),
content: z. string (),
}),
)
. output (PostSchema)
. mutation ( async ({ input }) => {
const post = await db.post. create ({
data: input,
});
return post;
});
As with the query procedure, export the mutation procedure from your feature module's index.ts
:
// ...
export * from "./create-post.ts" ;
To use the mutation you can use the apiClient
again:
import { apiClient } from '@shared/lib' ;
const formSchema = z. object ({
title: z. string (),
content: z. string (),
});
type FormValues = z . infer < typeof formSchema>;
export function MyClientComponent () {
const createPostMutation = apiClient.posts.createPost. useMutation ();
const {
handleSubmit ,
register ,
formState : { isSubmitting , isSubmitSuccessful },
} = useForm < FormValues >({
resolver: zodResolver (formSchema),
});
const onSubmit : SubmitHandler < FormValues > = async ({ title , content }) => {
try {
await createPostMutation. mutateAsync ({ title, content });
} catch {
// handle the error...
}
};
return (
< form onSubmit = { handleSubmit (onSubmit)}>
< input
type = "text"
{ ... register ( "email" )}
/>
< textarea
type = "text"
{ ... register ( "content" )}
/>
< button type = "submit" >
Create post
</ button >
</ div >
</ form >
);
}