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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With