Skip to main content

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

Introduction

In this blog post, we will discuss how to fetch and delete records using API routes in a Next.js application. API routes allow us to create, read, update, and delete data from a server using HTTP requests. We will explore how to fetch records from an API and display them on the user interface. Additionally, we will cover how to delete a specific record from the API and refresh the page to reflect the changes made.

Fetching Records

We built API routes to handle CRUD operations. We created a get method to return all the records, and an update method to update a record.

Now, let's focus on fetching all the records from the API and displaying them on the UI. To do this, we need to use the useState hook to create a state property that will hold the list of todos. We define the state property as an array of todo objects.

Next, we use the useEffect hook to make the API call and fetch the todos. We use the fetch API and specify the URL of the API todos. Additionally, we add a parameter to disable caching of the data.

Once we receive the response from the API, we extract the data using the response.json() method. Finally, we update the todos state property with the fetched data.

Component Code Example:


const [todos, setTodos] = useState([]);

useEffect(() => {
  const fetchData = async () => {
    const response = await fetch('API/todos', { cache: 'no-cache' });
    const data = await response.json();
    setTodos(data);
  };

  fetchData();
}, []);

Now that we have fetched the todos, let's display them on the UI. We can iterate over the todos array using the map function and create a list item for each todo. Inside the list item, we display the todo's name and username.

Component Code Example:


return (
  <ul>
    {todos.map((todo) => (
      <li key={todo.id}>
        <div className="todo-item">
          <span className="todo-name">{todo.name}</span>
          <span className="todo-username">{todo.username}</span>
        </div>
      </li>
    ))}
  </ul>
);

API Code Example:


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

By following these steps, we are able to fetch the todos from the API and display them on the UI.

Deleting Records

In addition to fetching records, we can also delete specific records from the API. To implement this functionality, we need to add a delete button for each todo item displayed on the UI. When the delete button is clicked, we will call a deleteTodo function and pass the todo's ID as a parameter.

Inside the deleteTodo function, we make a fetch API call to the delete route of the API, specifying the todo ID in the URL. We also set the method to 'delete' and include the necessary headers. Once the record is successfully deleted, we want to refresh the page to reflect the updated list of todos.

Component Code Example:


const deleteTodo = async (id) => {
  await fetch(`API/todos/${id}`, {
    method: 'delete',
    headers: {
      'Content-Type': 'application/json',
    },
  });

  window.location.reload();
};


API Code Example:


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

By adding the delete button and calling the deleteTodo function, we can delete a specific record from the API and refresh the page to see the updated list of todos.

Conclusion

In this blog post, we learned how to fetch and delete records using API routes in a Next.js application. We explored how to fetch records from an API and display them on the user interface. Additionally, we covered how to delete a specific record from the API and refresh the page to reflect the changes made.

By implementing these functionalities, we can create interactive applications that allow users to view and manage data effectively.

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...

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...

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...