Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make server component reflect data changes, made with server actions?

I have a server component ChatList, that fetches data from the database and displays it:

// server component

import Link from "next/link";
import db from "@/prisma";

export const ChatList = async () => {
  const chats = await db.chat.findMany();

  return (
    <ul>
      {chats.map((chat) => (
        <li key={chat.id}>
          <Link href={`chat/${chat.id}`}>{chat.name}</Link>
        </li>
      ))}
    </ul>
  );
};

Then I have a server action, that creates new record in the same table:

"use server";

import db from "@/prisma";

export const createChat = async (name: string) => {
  const newChat = await db.chat.create({
    data: { name },
  });
  return newChat;
};

This action is being invoked as form action prop.

Once new record is created, how do I tell the server component ChatList to refetch the data?

like image 607
eagor Avatar asked Mar 06 '26 21:03

eagor


1 Answers

You can achieve this by calling router.refresh() in your form action.

"use client";

import { useRouter } from "next/navigation";

// ...

const router = useRouter();

// ...

<form
  action={async (formData) => {
    const name = formData.get("name");
    if (typeof name === "string") {
      await createChat(name);
      router.refresh();
    }
  }}
>

You can also look into experimental useOptimistic hook to make the UI look more responsive.

like image 119
Igor Danchenko Avatar answered Mar 10 '26 09:03

Igor Danchenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!