I'm currently working on a Next.js project where I'm trying to delete a post by its id
using Prisma as my ORM and Zod for data validation. The client-side component sends a DELETE request to an API route on my server and should include the id
of the post to be deleted in the request body.
Here's my client-side function to handle deletion:
const handleDelete = async () => { if (!post?.id) return; try { await axios.delete(`/api/subreddit/post/delete/`, { data: { postId: post.id }, }); toast({ title: "Success", description: "Post was deleted successfully", }); router.refresh(); // Refresh the page or redirect the user. } catch (error) { console.log(error); // Log the error message return toast({ title: 'Something went wrong.', description: "Post wasn't deleted successfully. Please try again.", variant: 'destructive', }) }};
My server-side function looks like this:
export async function DELETE(req: Request) { try { const body = await req.json(); const { postId } = z.object({ postId: z.string(), }).parse(body); const session = await getAuthSession(); if (!session?.user) { return new Response("Unauthorized", { status: 401 }); } const post = await db.post.findUnique({ where: { id: postId, }, }); if (!post) { return new Response("Post not found", { status: 404 }); } if (post.authorId !== session.user.id) { return new Response("You do not have permission to delete this post", { status: 403 }); } await db.post.delete({ where: { id: postId, }, }); return new Response("Post Deleted"); } catch (error:any) { console.log('Error when deleting post:', error.message); if (error instanceof z.ZodError) { return new Response(error.message, { status: 400 }); } return new Response("Could not delete post at this time. Please try later", { status: 500 } ); }}
I'm getting the following error when I try to delete a post:
[ {"code": "invalid_type","expected": "string","received": "undefined","path": ["postId" ],"message": "Required" }]
This error suggests that postId
is undefined
. I'm not sure why this is happening because I'm providing a postId
in my DELETE request from the client side. Any help would be appreciated!
I've tried to console log the request and try to figure out the issue from there, but I was unsuccessful.