Encountering difficulty in removing a record from the database utilizing Prisma with Next.js API routes

Currently, I am in the process of developing a Todo manager using Next.js 13, Prisma, and MySQL. In order to include a feature that allows users to delete a todo item, I have implemented the use of a Link tag for the delete button within my code:

...
<Link href={`/api/todo/${id}`}>
          <MdDelete className="bg-red-400 hover:bg-red-600 p-1 text-3xl rounded-xl" />
</Link>
...

The value of id is passed as a prop to the component. The route defined in /app/api/todo/[id]/route.ts looks like this:

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

export async function DELETE(
  req: Request,
  { params }: { params: { id: string } }
) {
  await prisma.todo.delete({
    where: {
      id: params.id,
    },
  });
  return NextResponse.json({ message: "done" });
}

However, upon clicking the Link, it redirects to the URL

http://localhost:3000/api/todo/clkgkh3t70000p1947hi24a3k
and displays an error page:

https://i.stack.imgur.com/4YOwp.png

where clkgkh3t70000p1947hi24a3k represents the id being passed.

Is there a solution to this problem? Alternatively, what other method can be used to remove the Todo Item?

Answer №1

The Link component acts as a wrapper for the standard HTML a element, which is typically used to navigate to a new page. If you want to execute a function on click, you should use a button with an onClick event handler:

<MdDelete
  onClick={async (e) => {
    e.preventDefault() 
    await fetch(`/api/todo/${id}`, { method: "DELETE" });
    // Following this, you can redirect or update a state, etc...
  }}
  className="bg-red-400 hover:bg-red-600 p-1 text-3xl rounded-xl"
/>

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

Using an Object as a parameter in a Typescript function

I am currently working on an Angular component that includes a function. Within this function, I need to pass an Object as a parameter and invoke the function with these parameters. It has been some time since I last worked with Angular, where "any" was ty ...

Front-end user authentication concerns when employing JWT

Currently, my focus is on transitioning to the MERN stack and incorporating an authentication module using Next.js (front-end) + Node.js (for scalability). I am utilizing JWT token method for authentication and have some concerns: Storing tokens in coo ...

Encountering error while loading NextJS in development mode (_devPagesManifest.json fetch and 'includes' of undefined)

Lately, I've been encountering some issues while working on my NextJS app. Initially, when I run npm run dev, everything seems to work fine. However, after a few hot reloads or manual page refreshes, the app starts loading indefinitely and becomes un ...

The InAppBrowser seems to have trouble loading pages with cookies when I attempt to navigate back using the hardware back button

In my Ionic/Angular application, I utilize the InAppBrowser plugin to access a web application for my company. The InAppBrowser generally functions properly; however, there is an issue with a cookie within the web application that controls filters for cert ...

What could be causing Next Auth to trigger a Client Fetch Error right when the page is loaded?

I followed a YouTube tutorial to create a full-stack website using NextAuth for authentication with Google providers. I have ensured that the correct Google ID and secret are being used, and I have added the callback URL on console.cloud.google as well (ca ...

Error TS2403: All variable declarations following the initial declaration must be of the same type in a React project

While developing my application using Reactjs, I encountered an error upon running it. The error message states: Subsequent variable declarations must have the same type. Variable 'WebGL2RenderingContext' must be of type '{ new (): WebGL2 ...

Creating a higher order component (HOC) that utilizes both withRouter and connect functions in React

I am currently working with the following stack: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87f5e2e6e4f3c7b6b1a9b6b4a9b6">[email protected]</a> <a href="/cdn-cgi/l/email-protection" class="__cf_email__" dat ...

Exploring the capabilities of renderOption within Material-UI's AutoComplete functionality

Hey there, I've been pondering a question lately and could really use some help. I've been trying to set up my autocomplete feature to display a label in the options while having a different value. After doing some research, I learned about usin ...

Verify user authentication status on the server using Vercel and NextAuth

After successfully running my blog on localhost, I encountered an issue when deploying it on Vercel. The page to create a post kept returning error 504 with no additional information in the logs. I made sure to update the NEXTAUTH_URL with the URL provide ...

The error message "GetStaticPaths Error: Objects are not valid as a React child" indicates that an object was found when expecting a different type of data in a React component. To render a collection

I've encountered an issue while mapping the response from my get staticpath. Despite trying to destructure the response object, I haven't been successful. Consequently, when I select a single item, an error message is displayed. Feel free to chec ...

Converting information from a model into individual variables

I'm a newcomer to typescript and angular, and I've been attempting to retrieve data from firebase using angularfire2. I want to assign this data to variables for use in other functions later on. I am accustomed to accessing object members using d ...

Developing with Ionic 2 allows you to efficiently run a background service using Cordova

I am currently using Ionic 2 and I have a requirement for my app to perform certain tasks even when it is closed, similar to how Gmail continues to provide notifications all the time. After some research, I came across this documentation: https://ionicfr ...

Typescript challenge: Implementing a route render attribute in React with TypeScript

My component has props named project which are passed through a Link to a Route. Here's how it looks (the project object goes in the state extended property): <Link to={{ pathname: path, state: { project, }, }} key={project. ...

Creating a Bottom Sliding Menu in Ionic 2

Hey there! I'm working on something that might not fit the typical definition of a sliding menu. It's not for navigation purposes, but rather to house some data. My idea for this actually comes from Apple Maps: https://i.stack.imgur.com/hL1RU.jp ...

Error encountered when attempting to reference multiple Select MenuItems in Material UI

Recently, I've been encountering a perplexing error when attempting to open a multiple Select in React+Next.js using Material UI: Error: Argument appears to not be a ReactComponent. Keys: retry This issue seems to be related to a ref. It occurs with ...

Angular TSLint: Proceed to the following stage despite any encountered errors

I'm facing issues with TSLint in my Azure Devops Build Pipeline. Despite encountering lint errors, I need the build pipeline to proceed to the next step. How can I achieve this? Command Line: - script: | npm run lint > tsLintReport.txt ...

Vercel seems to have trouble rendering NextJS Images

I'm currently facing a small issue with my project. I attempted to deploy my Next.Js project on Vercel, but I encountered an image rendering problem. Images that rendered perfectly during testing are not displaying when the project is deployed on Verc ...

The pivotal Angular universal service

In my application, I have the need to store global variables that are specific to each user. To achieve this, I created a Service that allows access to these variables from any component. However, I am wondering if there is a way to share this service t ...

Navigating to NextAuth's login page after signing in with NextJS

After spending the past 12 hours troubleshooting the same issue and scouring countless online forums, I am still unable to find a solution that meets my requirements. Despite following the NextAuth and NextJS tutorial for setting up authentication, I am s ...

What steps are needed to configure ESLint to exclusively analyze .ts files?

I need ESLint to exclusively focus on processing .ts files and not .js files. In order to achieve that, I made a .eslintignore file and included the following lines: *.js **/*.js Nevertheless, it appears that ESLint is disregarding this file. Is there so ...