Issue encountered while attempting to remove a post from my Next.js application utilizing Prisma and Zod

Currently, I'm immersed in a Next.js project where the main goal is to eliminate a post by its unique id. To carry out this task efficiently, I make use of Prisma as my ORM and Zod for data validation. The crux of the operation involves the client-side component dispatching a DELETE request to an API route on my server, alongside including the specific id of the post earmarked for deletion within the request body.

Let me walk you through my client-side approach when it comes to managing deletions:

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); // Record any encountered errors
    return toast({
      title: 'Something went wrong.',
      description: "Post wasn't deleted successfully. Please try again.",
      variant: 'destructive',
    })
  }
};

To complement this, my server-side mechanism is structured like so:


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

An issue I encounter while endeavoring to erase a post manifests in the form of:


[
  {
    "code": "invalid_type",
    "expected": "string",
    "received": "undefined",
    "path": [
      "postId"
    ],
    "message": "Required"
  }
]

This particular hiccup alludes to the fact that postId emerges as undefined. The mystifying aspect of this dilemma lies in the fact that, indeed, a valid postId enters the fray via my client-side DELETE request. Any insights or suggestions on how to rectify this anomaly would be genuinely appreciated!

Attempts were made to peruse the request logs and pinpoint the root cause of the matter, unfortunately, they did not yield successful results.

Answer №1

After implementing the latest update for next.js, the reported issues were successfully resolved due to a previously identified bug within the system.

Answer №2

When I tested your script, I decided to substitute a hardcoded string "test" for the Axios body.

Surprisingly, this adjustment prevented any parsing issues and the code executed smoothly.

To troubleshoot further, ensure that the post.id variable is definitively a string; otherwise, there shouldn't be any glitches.

Below is the example code snippet I utilized:

Server-side implementation:

import { NextResponse } from "next/server"
import { z } from "zod"

export async function DELETE(req: Request) {
  try {
    const body = await req.json()
    const { postId } = z
      .object({
        postId: z.string(),
      })
      .parse(body)

    return NextResponse.json("success", { status: 200 })
  } catch (error: any) {
    console.log("An error occurred while attempting to delete the post:", error.message)
    if (error instanceof z.ZodError) {
      return new Response(error.message, { status: 400 })
    }

    return new Response(
      "Unable to delete the post at this moment. Please try again later.",
      { status: 500 }
    )
  }
}

Client-side version:

"use client"

import axios from "axios"

import { Button } from "@/components/ui/button"

const page = () => {
  return <Button onClick={handleDelete}>delete</Button>
}
export default page

const handleDelete = async () => {
  try {
    await axios.delete(`/api/delete`, {
      data: { postId: "test" },
    })
  } catch (error) {
    console.log(error)
  }
}

Answer №3

After encountering a similar issue, I found the solutions provided here to be quite helpful.

In my opinion, the crux of the problem lies in the formatting of the input parameters. I sincerely hope that your problem has been resolved successfully! (Apologies for any language or code deficiencies on my part.)

I implemented Prisma in this scenario↓

Client-side code snippet:

export async function deleteFur(param) {
  try {
    console.log("param", param); // {id: 1}
    const raw = await axios.delete("/api/furniture", {
      data: JSON.stringify(param), // json
    });
    console.log(raw);
    const { data } = raw;
    return data;
  } catch (err) {
    console.error(err);
  }
}

Server-side code snippet:

import db from "@/lib/db";
import { NextResponse } from "next/server";

export async function DELETE(req, res) {
  try {
    const payload = await req.json(); // retrieve it
    const deletedAppliance = await db.appliance.delete({
      where: payload,
    });
    return NextResponse.json({
      status: 201,
      message: deletedAppliance,
    });
  } catch (err) {
    return NextResponse.error({ status: 500, message: err });
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can TypeScript support promise chaining in a functional way?

It appears that in the realm of JavaScript, one has the capability to execute: function extendPromise(promise) { return promise.then(new Promise(() => {})); } However, when incorporating types into the mix, such as function extendTypeScriptPromis ...

Effortlessly transferring images using Axios in Node.js: A guide

Previously, I utilized ApiSauce to send listings from my React Native application to a Node.js server with Multer. I made the switch to Axios, and everything went smoothly except for the image uploading component. export const add = (listing, onUploadPro ...

Implementation of multiple angular guards causing a crash on the page

I have been attempting to implement separate guards for distinct pages. Essentially, I am checking a boolean parameter to determine if a user is logged in or not. Below are the two guard.ts codes that I am using: export class IsAuthenticatedGuard implemen ...

Unable to locate module '.next/server/font-manifest.json'

I'm encountering a frustrating issue while attempting to deploy my nextjs app with server rendering. The app was created using Azure Pipelines and then uploaded to a production server that runs on a Linux operating system. Below is the configuration ...

Tips for integrating jwt token into axios request

I am facing an issue with my backend endpoint. I can successfully retrieve a list of customers using jwt token on Postman, but when I try to fetch the list from a React app using axios get request, it fails. After reading through this question, I implemen ...

Is the getServerSideProps method filled with data if it already has a cached result from an API request?

I am considering using nextjs for an upcoming project. The frontend of this project will be a React application that utilizes getServerSideProps. Initially, the frontend will not have any content to display, as the server side props dictate which UI should ...

What is the process for defining a generic function to convert to an array in TypeScript?

Here is a versatile function that wraps any value into an array: const ensureArray = <T,>(value?: T | T[]): T[] => { if (Array.isArray(value)) return value if (value === undefined) return [] return [value] } const undef = undefined ensureAr ...

Steps to align the outline of VS Code with the current location in the editor

When working in a language known for its large and complex files, it can be frustrating to navigate through the code. I often find myself scrolling up and down multiple times just to locate the current function name. This is why I am looking for a way to e ...

ReactJS Typescript Material UI Modular Dialog Component

Hello, I need help with creating a Reusable Material UI Modal Dialog component. It's supposed to show up whenever I click the button on any component, but for some reason, it's not displaying. Here's the code snippet: *********************TH ...

Is Angular capable of determining which module to load for the frontend, or does it always need to load the entire application with all modules?

Is it possible for Angular 2 to selectively load specific modules for the frontend, or does it always have to load the entire application with all modules included? ...

Encountering an issue during the deployment of a next.js project on netlify. Any suggestions on how to address it

I'm facing an issue while trying to deploy a next.js project on Netlify by selecting a git repo. Every time I attempt to deploy, I encounter an error. I've tried removing the package-lock.json file and even downgrading the versions of react and r ...

Vercel deployed Next-App encountering issues: Request for a new refresh token triggers an unexpected 304 Not Modified response

For my latest project, I developed a Next.js frontend app and deployed it on Vercel, along with a Django backend app on Heroku. The authentication mechanism I used involves JWTs and a connection between the Next.js frontend and Django backend through a Nex ...

What is the reason behind the occurrence of `(User & { _id: Schema.Types.ObjectId; }) | null` when calling findById?

Today marks my debut using typescript and mongoose. Here's a glimpse of what I've worked on. Type export interface User extends Document { _id: ObjectId; lastName: string; } Schema const userSchema = new Schema<User>({ lastName: { t ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

Official Docs style sidebar for NextJS

The official documentation for NextJS has a sleek sidebar design with both style and functionality. I am curious if it is possible to access the source code of the sidebar on the official website, or perhaps find a React/Next package that supports the Nex ...

Accurate function calls with multiple parameters in TypeScript

As a beginner in TypeScript and currently exploring its integration with AngularJS, I am facing a particular issue where the compiler is not detecting an error. In Angular, a resource provider typically includes a get() method that returns an instance of ...

Encountering an Issue: The formGroup function requires an instance of a FormGroup. Kindly provide one

I am a beginner with Angular 2 and despite reviewing numerous stack overflow answers, I still can't resolve my issue. I have recently started learning about angular reactive forms and wanted to try out my first example but I'm facing some diffic ...

Fixing Email Validation Error in AngularLearn how to troubleshoot and resolve

I'm encountering an issue when trying to develop an email center using regex pattern, as I'm receiving a validator error in HTML. I have already installed ngx-chips and angular-editor, imported all the necessary modules and dependencies. Here is ...

I encountered an issue with my TypeScript function in Angular, as it is unable to process multiple uploaded files

I'm having trouble with my TypeScript function in Angular that is unable to read multiple uploaded files. fileUpload(event: Event) { const self = this; this.imageUploadInp = event.target as HTMLInputElement; this.imageUploadInp.addEventLis ...