deletePost in Server Actions
Unanswered
Scarlet Ibis posted this in #help-forum
Scarlet IbisOP
Hello,
I have:
When I click the button to delete the post, it will give me 404 page (but the post is deleted from the db)
What is the issue?
I have:
export async function deletePost(formData: FormData) {
try {
const id = formData.get("id") as string;
await prisma.post.delete({
where: { id: id }
});
revalidatePath('/posts');
} catch (error) {
console.error('Error deleting post:', error);
}
}
When I click the button to delete the post, it will give me 404 page (but the post is deleted from the db)
What is the issue?
<form action={deletePost}>
<input type="hidden" name="id" value={post.id} />
<button type="submit">delete post</button>
</form>
5 Replies
are you checking anywhere if the post exists and returning notFound if it doesn't?
@Yi Lon Ma are you checking anywhere if the post exists and returning notFound if it doesn't?
Scarlet IbisOP
Yes, in the PostPage:
const { slug } = await params;
const post = await getPost(slug)
if (!slug || !post) return notFound();
@Scarlet Ibis Yes, in the PostPage:
ts
const { slug } = await params;
const post = await getPost(slug)
if (!slug || !post) return notFound();
yea since the post is deleted, the getPost returns null and triggers notFound
@Yi Lon Ma yea since the post is deleted, the getPost returns null and triggers notFound
Scarlet IbisOP
but if I added revalidatePath to /posts should it just move me there?
Thanks for trying to help btw