Skip to main content

The Complete Guide to CRUD Operations in Next.js with Prisma Client Part - 4

Introduction

In this blog post, we will explore how to create and update records using Next.js and Prisma. We will cover the process of setting up the necessary API routes and implementing the functionality to add and edit records in a simple todo application.

Setting Up API Routes

To begin, we need to create the API routes that will handle the creation and updating of records. In Next.js, API routes are stored in the "pages/api" folder. We will create a file named "todos.js" to handle our todo-related operations.

Inside the "todos.js" file, we will define the necessary routes for creating, updating, and deleting todos. For example, when we hit the "/api/todos" URL, it will be handled by the "index.js" file in the "todos" folder.

By default, if we don't specify the method name in the URL, it will be treated as a GET request. For other operations like create, update, and delete, we need to set the appropriate method.

Creating a New Todo

When creating a new todo, we will make a POST request to the "/api/todos" route. Inside the corresponding route handler, we will retrieve the form data and perform the necessary actions to create a new record in the database.

First, we will check if the request is for creating a new todo. If it is, we will extract the todo object from the form data and use it to make a POST request to the Prisma Todos table. We will also reset the form to clear the input fields.

Component Code to call the API Route Page.tsx

      
       fetch('/api/todos/', {
        cache: 'no-store',
        body: JSON.stringify(form),
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'POST'
      }).then(() => {
        setForm({ name: '', userName: '', id: '' })
        refreshPage()
      })
      
      

API Route Code to call the API Route /pages/api/todos.ts

      
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method === 'POST') {
        try {
            const { name, userName } = req.body;
            const todos = await prisma.todos.create({
                data: {
                    name,
                    userName
                }
            })
            res.status(200).json(todos);
        } catch (e) {
            res.status(500).json(e);
        }
    }
}
      
      

Updating an Existing Todo

To update an existing todo, we will make a PUT request to the "/api/todos/{id}" route, passing the todo ID as a parameter. Inside the route handler, we will retrieve the form data and update the corresponding record in the database using the ID.

Similar to the create operation, we will check if the request is for updating a todo. If it is, we will extract the todo object from the form data and use it to make a PUT request to the Prisma Todos table. We will also reset the form to clear the input fields.

Component Code to call the API Route Page.tsx

      
       async function editTodo(name: string, userName: string, id: string) {
         setForm({ name, userName, id })
         setNewTodo(false)
       }
       fetch('/api/todos/' + form.id, {
        cache: 'no-store',
        body: JSON.stringify(form),
        headers: {
          'Content-Type': 'application/json'
        },
        method: 'PUT'
      }).then(() => {
        setForm({ name: '', userName: '', id: '' })
        setNewTodo(true)
        refreshPage()
      })
      
      

API Route Code to call the API Route /pages/api/todos/[id].ts

      
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    if (req.method === 'PUT') {
        try {
            const todoId = req.query.id;
            const { name, userName } = req.body;
            const todos = await prisma.todos.update({
                data: {
                    name, userName
                },
                where: {
                    id: Number(todoId)
                }
            })
            res.status(200).json(todos);
        } catch (e) {
            res.status(500).json(e);
        }
    }
}
      
      

Conclusion

In this blog post, we learned how to create and update records using Next.js and Prisma. We explored the process of setting up the necessary API routes and implementing the functionality to add and edit records in a simple todo application.

By following the steps outlined in this blog post, you can easily create a robust CRUD system using Next.js.

Made with VideoToBlog

Comments

Popular posts from this blog

Ultimate Guide to Implementing DELETE Operations in Next.js with Prisma

In this tutorial, we will learn how to delete a post in Next.js using the API and UI code. Deleting a post requires making changes to the folder structure and implementing the delete method. Let's dive in! Changing the Folder Structure Currently, the folder structure for the API is not suitable for deleting posts. We need to pass an ID to delete a specific post. To enable this functionality, we will need to alter the folder structure. Here's how: Create a new folder named "posts" within the API directory. Move the existing file into the "posts" folder. Rename the file to "index". Now, when we access the "posts" endpoint, it will work without specifying the file name. Implementing the Delete Method To delete a post, we need to create a new file in the "posts" folder and pass the I...

Creating API Routes for a Full Stack Application

In this blog post, we will explore how to create API routes for a full stack application. API routes are essential for connecting the frontend components to the backend database and fetching data. We will specifically focus on creating the API routes and endpoints for making API calls and retrieving data. Setting up the Database Before we dive into creating the API routes, we need to set up the database. In this example, we will be using a local PostgreSQL database. To connect to the database, we have a schema file that defines a table called "todos" with four fields: id, name, username, and created_at. Currently, we have two records in the todos table. The next step is to write the API routes to connect to the database and fetch the data. Using Prisma for API Routing To create the API routes, we will be using the Prisma library, specifically the Prisma client. The Prisma client allows us to connect to the database and execute queries. To start with the API rout...

How to use Redux in Next.js

Introduction In this blog post, we will explore how to use Redux with Next.js and create todo and disptach it to Redux store and and pass the todo (state) to a Page and display the created Todo. We will cover the process of setting up the necessary Redux store and cover the end to end flow. Create Next.js application npx create-next-app@latest Install dependencies npm install --save @reduxjs/toolkit npm install --save react-redux npm install --save redux-persist Folders and files needed Create folder lib under src folder(src/lib) Create Interface Todos under lib folder (lib/Todos.ts) export interface ITodo { todosState: [Todo] } export interface Todo { todoName: string, description: string, userName: string, id: string } Create folder store under lib (lib/store) Create fi...