0

I have two files inside mine /api/ folder. create-comment.tsx and delete-comment.tsx the create comment works perfectly fine. with method "POST" but using method "DELETE" to remove a single item from the back-end returns in:

DELETE http://localhost:3000/api/delete-comment 500 (Internal Server Error)

My Comments.tsx (component) is where I am firing a function on click and running the API file:

import { Trash } from "phosphor-react";

import { dateFormat } from "@lib/helpers";
import { Comments } from "types/typings";

const handleDelete = async (data: any) => {
  await fetch("/api/delete-comment", {
    method: "DELETE",
    body: JSON.stringify(data),
  });
};

const Comments = ({ comments, session }: Comments) => {
  const sortedComments = comments.sort(
    (a, b) =>
      new Date(b._createdAt).valueOf() - new Date(a._createdAt).valueOf()
  );

  return (
    <div className="w-full px-4 pb-16 pr-4 mx-auto mt-6 md:pt-4 md:max-w-4xl">
      <div className="flex flex-col gap-8 leading-relaxed text-md text-navyBlue">
        {!sortedComments.length && (
          <p className="text-lg font-bold">No comments yet...</p>
        )}

        {sortedComments.map(
          ({ _id, name, publishDate, comment, avatarUrl, email }: any) => (
            <div key={_id} className="relative grid grid-cols-12 gap-4">
              {session && (
                <Trash
                  onClick={() => handleDelete(_id)}
                  size={20}
                  color="#ff0000"
                  weight="duotone"
                  className="absolute top-0 right-0 z-10 cursor-pointer"
                />
              )}
              <div className="col-span-2 md:col-span-1 avatar">
                {avatarUrl && (
                  <div className="w-12 h-12 rounded-full ring ring-[#65c3c8] ring-offset-2">
                    <img src={avatarUrl} alt="" />
                  </div>
                )}
              </div>
              <div className="relative md:-mt-2 col-span-full md:col-span-11">
                <h4 className="font-bold">{name}</h4>
                <time>{dateFormat(publishDate)}</time>
                <p className="mt-1">{comment}</p>
              </div>
            </div>
          )
        )}
      </div>
    </div>
  );
};

export default Comments;

My /api/delete-comment.tsx:

import type { NextApiRequest, NextApiResponse } from "next";

import SanityClient from "@sanity/client";

import { config } from "@lib/config";

const client = SanityClient(config);

export default async function deleteComment(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { _id } = JSON.parse(req.body);

  try {
    client.delete(_id);
    console.log("Comment deleted");
  } catch (error) {
    console.log(error);
    return res.status(500).json({ message: `Couldn't remove comment`, error });
  }

  res.status(200).json({ message: "Comment deleted" });
}

Am I doing something wrong here? or missing anything which causes to give me this error?

Galanthus
  • 1,958
  • 3
  • 14
  • 35
  • 1
    What is the error you get in the `catch`? Note that `client.delete()` returns a promise, so you should be doing `await client.delete(_id);` here. – Alexander Staubo Apr 12 '22 at 10:16

0 Answers0