currently learning next.js and kind of struggling. When the delete text is clicked, it should trigger the toggleDelete function. it successfully deletes the data from the db, but doesn't immediately reflect the changes on the UI. I've tried a couple of things but keep ending up with runtime errors left and right.
目前正在学习next.js,有点吃力。当点击删除文本时,应该会触发toggleDelete函数。它成功地从数据库中删除了数据,但不会立即将更改反映在用户界面上。我尝试了几种方法,但总是以运行时错误而告终。
How would you go about this? thanks!
你将如何着手这件事?谢谢!
import { TodoItem } from "@/components/TodoItem";
import { prisma } from "@/db";
import Link from "next/link";
function getTodos() {
return prisma.todo.findMany();
}
async function toggleTodo(id: string, complete: boolean) {
"use server";
await prisma.todo.update({ where: { id }, data: { complete } });
}
async function toggleDelete(id: string) {
"use server";
await prisma.todo.delete({ where: { id } });
}
export default async function Home() {
const todos = await getTodos();
return (
<>
<header className="flex justify-between items-center mb-4">
<h1 className="text-2xl">Todos</h1>
<Link
className="border border-slate-300 text-slate-300 px-2 py-1 rounded hover:bg-slate-700 focus-within:bg-slate-700 outline-none"
href="/new"
>
New
</Link>
</header>
<ul className="px-4">
{todos.map((todo) => (
<TodoItem key={todo.id} {...todo} toggleTodo={toggleTodo} toggleDelete={toggleDelete} />
))}
</ul>
</>
);
}
"use client";
import { format } from 'date-fns';
type TodoItemProps = {
id: string;
title: string;
complete: boolean;
createdAt: Date;
toggleTodo: (id: string, complete: boolean) => void;
toggleDelete: (id: string) => void;
};
export function TodoItem({ id, title, complete, createdAt, toggleTodo, toggleDelete }: TodoItemProps) {
const formattedCreatedAt = format(createdAt, 'MM/dd/yyyy, hh:mm:ss a');
return (
<li className="flex justify-between items-center">
{/* option to cross it out */}
<div className="flex items-center">
<input
id={id}
type="checkbox"
className="cursor-pointer peer"
defaultChecked={complete}
onChange={(e) => toggleTodo(id, e.target.checked)}
/>
<label
htmlFor={id}
className="cursor-pointer ml-2 peer-checked:line-through peer-checked:text-slate-500"
>
{title}
</label>
</div>
{/* when was it made */}
<div className="text-right text-xs">
Created - {formattedCreatedAt}
</div>
{/* delete option */}
<div className="flex items-center">
<div>
<p className="text-xs cursor-pointer peer" onClick={() => toggleDelete(id)}>delete</p>
</div>
</div>
</li>
);
}
更多回答
优秀答案推荐
You can revalidate the cache within the delete function.
您可以在DELETE函数中重新验证缓存。
https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations
Https://nextjs.org/docs/app/building-your-application/data-fetching/forms-and-mutations
// import function to server component
import { revalidatePath } from 'next/cache'
//call function in your delete method
async function toggleDelete(id: string) {
"use server";
await prisma.todo.delete({ where: { id } });
revalidatePath('/')
}
更多回答
我是一名优秀的程序员,十分优秀!