API

Mutations

Learn how to mutate data on the server.

As we saw in adding new endpoint we can define mutations in the same way as queries.

Of course, as for the queries, we can run mutations on the server-side or client-side, let's see how it works.

Server actions

In Next.js, the common approach to perform mutations is to use server actions. They're especially useful for form submissions.

With our api it's as simple as possible - it's just a function call performed on the server.

For example, you can define an action to create a post like this:

lib/actions.ts
"use server";
 
import { revalidatePath } from "next/cache";
 
import { api } from "~/lib/api/server";
 
export async function createPost(post: PostInput) {
  try {
    await api.posts.create(post);
  } catch (error) {
    handleError(error);
  }
 
  revalidatePath("/posts");
}

In the above example we're also using revalidatePath to revalidate the path /posts to fetch the updated list of posts.

useMutation hook

On the other hand, if you want to perform a mutation in the client-side, you can use the useMutation hook that comes straight from the integration with Tanstack Query.

form.tsx
import { api } from "~/lib/api/react";
 
export function CreatePost() {
  const utils = api.useUtils();
  const { mutate } = api.posts.create.useMutation({
    onSuccess: () => {
      toast.success("Post created successfully!");
      utils.posts.getAll.invalidate();
    },
  });
 
  return <form onSubmit={handleSubmit(mutate)} />;
}

Last updated on

On this page

Ship your startup everywhere. In minutes.Get TurboStarter