Skip to content

Instantly share code, notes, and snippets.

@t3dotgg
Created February 26, 2024 21:21
Show Gist options
  • Save t3dotgg/28653e546a7d43789e0d4ce758d4924f to your computer and use it in GitHub Desktop.
Save t3dotgg/28653e546a7d43789e0d4ce758d4924f to your computer and use it in GitHub Desktop.
Example of a page refreshing content using unstable_cache in Next.js App Router
import { revalidateTag, unstable_cache } from "next/cache";
import { db } from "~/server/db";
import { todoItems } from "~/server/db/schema";
const getTodos = unstable_cache(
async () => {
return await db.query.todoItems.findMany();
},
["todoItems"],
{
tags: ["todos"],
},
);
async function createTodoItem(formData: FormData) {
"use server";
const todoName = formData.get("todoName");
if (!todoName || typeof todoName !== "string") return;
await db.insert(todoItems).values({
name: todoName,
});
revalidateTag("todos");
}
export default async function HomePage() {
const todoList = await getTodos();
return (
<main className="flex flex-col">
{todoList.map((todo) => (
<div key={todo.id}>{todo.name}</div>
))}
<form action={createTodoItem}>
<input type="text" name="todoName" className="text-black" />
<button type="submit">Create Todo</button>
</form>
</main>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment