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.
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>
);
}