skip to Main Content

I really don’t know why, but when I try to fetch data and put it in the body of my response, it says undefined (in the console). I have almost 2 identical components. One uses a POST method and returns a populated body, the other uses a DELETE method and returns an undefined body. I am using a Prisma schema.

This is the POST that works and returns a body for the API

export default function Product({
  id_product,
  name,
  link_image,
  price,
}: ProductProps) {
  const [test, testing] = useState(false);
  const { push: relocate } = useRouter();

  const onAddToCart = async () => {

    let response = await fetch("/api/addToCart", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({
        id_product: id_product,
      }),
    });

    if (response.ok) {
      toast.success(`${name} was added to the cart`);
    } else {
      toast.error(`${name} is already in your cart`);
    }
  };

This is start of the API for that function, const { id_product } = req.body works.

async function handlePost(req: NextApiRequest, res: NextApiResponse) {
    const session = await getServerSession(req, res, authOptions);
    const client = connexion()
    const { id_product } = req.body;
 
    const user = await client.user.findFirst({
        where: { email: session?.user?.email || undefined}
    })

    let cart = await client.cart.findFirst({
        where: {id_user: user?.id_user}
    })

And this is what I’m having trouble with, the component is basically the same, except the method :

type ProductProps = products;

export default function ProductItem({
  id_product,
  description,
  publication_date,
  author,
  name,
  link_image,
  price,
}: ProductProps) {
  const onDeleteFromCart = async () => {
    let data = {
      id_product: id_product
    }
    let response = await fetch("/api/deleteFromCart", {
      method: "DELETE",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    });
    if (response.ok) {
        toast.success(`${name} was succesfully removed from your cart`)
    }
    else {
        toast.error(`Error`);
      }
  };

This is the API for, const {id_product} = req.body is undefined

async function handleDelete(req: NextApiRequest, res: NextApiResponse) {
    const session = await getServerSession(req, res, authOptions);
    const client = connexion()
    const  { id_product } = req.body
console.log(id_product)
    const user = await client.user.findFirst({
        where: { email: session?.user?.email || undefined}
    });
 
    let cart = await client.cart.findFirst({
        where: {id_user: user?.id_user}
    });
    let cart_item = await client.cart_item.findFirst({
        where: {
            id_cart: cart?.id,
            id_product: id_product
        }
    })

I’ve been trying to solve this problem for a couple of hours now and I didn’t progress at all.

2

Answers


  1. delete requests doesn’t contains body, you can try using patch method instead if you need a body in this request

    Login or Signup to reply.
  2. This used to work until a very recent update. There’s a bunch of issues on GIthub but I don’t know that any maintainer of Next.js has responded yet. It’s currently blocking us from updating. I get that it’s not typical, but this is a breaking change by Next.js, and I don’t want to have to migrate all our DELETE endpoints :(.

    https://github.com/vercel/next.js/issues/49353

    https://github.com/vercel/next.js/issues/48096

    https://github.com/vercel/next.js/issues/48898

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search