Created
February 26, 2024 21:21
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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