React.js

React Fetch and Delete API

Welcome readers, in this tutorial, we will implement a fetch and delete api in a react application.

1. Introduction

React is a flexible javascript library responsible for building reusable UI components. It is an open-source component-based frontend library responsible only for the view part of an application and works in a virtual document object model. But before that let us take a look at the differences between angular and react –

AngularReact
Complete frameworkLibrary
Object-oriented programmingExtension to the javascript library and its internal architecture is based on jsx
Based on the model view controller and real document object modelBased on the virtual document object model

To understand a practical implementation of the react library let us go through some hands-on exercises.

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

1.1.1 Setting up react js project

Once the Nodejs setup is successful we will use the below command to install the react library and set up the project. Do note that the npx package is available with the npm 5.2 version and above.

Create project structure

$ npx create-react-app fetch-and-delete-app

The above command will take some time to install the react library and create a new project named – get-fetch-app as shown below.

Fig. 2: Project structure

2. Fetch and Delete API in React Application

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up backend project

To perform the fetch and delete api call in react application I will be using a separate nodejs application that exposes the get and delete endpoints to fetch and delete the user. Since the nodejs application is out of the scope of this tutorial hence I am skipping it for brevity. However, you can download the source code from the Downloads section.

2.2 Setting up the react code

2.2.1 Creating the implementation file

Add the below code to the app.js file responsible to handle the implementation. We will use the get endpoint to fetch the data and show it in an html table. Each record will have a delete button responsible to delete the record. Once the data is deleted a success response message will be shown and auto refresh after three seconds. The data will be fetched and deleted via the endpoints exposed in the backend application running on the nodejs server at port number – 9500.

App.js

import React, { useState } from "react";
import "./App.css";

// a separate nodejs application is running in the backend

function App() {
  let [data, setData] = useState(null);
  let [status, setStatus] = useState(null);

  async function getUsers() {
    setStatus(null); // clear status on retrigger
    try {
      // get all users' endpoint
      const res = await fetch("http://localhost:9500/all");
      if (!res.ok) throw new Error("Some error has occurred.");

      const users = await res.json();
      setData(users.data);
    } catch (err) {
      // console.log("error occurred", err);
      setStatus({
        type: "error",
        message: err.message,
      });
    }
  }

  async function deleteUser(param) {
    setStatus(null); // clear status on retrigger
    try {
      // delete user endpoint
      const res = await fetch(`http://localhost:9500/id/${param}`, {
        method: "delete",
      });

      setStatus({
        type: "pass",
        status: res.status,
        message: `${param} deleted`,
      });

      // if deletion is successful reload the table after x seconds
      setTimeout(function () {
        getUsers();
      }, 3000);
    } catch (err) {
      // console.log("error occurred", err);
      setStatus({
        type: "fail",
        message: err.message,
      });
    }
  }

  return (
    <div className="App">
      <h1>React crud - FETCH and DELETE example</h1>
      <button onClick={getUsers}>Get all users</button>
      <div id="data">
        {data !== null && data.length > 0 && (
          <table className="usersTbl" border="1">
            <thead>
              <tr>
                <td>
                  <strong>Id</strong>
                </td>
                <td>Name</td>
                <td>Email</td>
                <td>Age</td>
                <td>Delete</td>
              </tr>
            </thead>
            <tbody>
              {data.map((item, i) => (
                <tr key={i}>
                  <td>{item.id}</td>
                  <td>{item.name}</td>
                  <td>{item.email}</td>
                  <td>{item.age}</td>
                  <td>
                    <button onClick={() => deleteUser(item.id)}>
                      Click me
                    </button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        )}

        {data !== null && data.length === 0 && <p>No items were found...</p>}
      </div>
      <div id="message">
        {status !== null && status?.type === "pass" && (
          <p>
            Resource {status?.message}. Status_code= {status?.status}
          </p>
        )}
        {status !== null && status?.type === "fail" && <p>{status?.message}</p>}
      </div>
    </div>
  );
}

export default App;

3. Run the React Fetch API App

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run start

The application will be started on the default port. In case the application does not get started on the default port you can change the port number as per your requirement. I have changed the default port to 2000.

Fig. 3: Application run

4. Demo

The application will be started in the default browser as shown below.

Fig. 4: Application demo

Click on the Get all users button to fetch the details from the get-all-users backend api running on the nodejs application. If everything goes well the data will be shown in the html table. Each record in the html table will have a delete button to delete the data from the db via the delete backend api.

Fig. 5: Data fetched successfully

Once the delete button is clicked the data will be deleted and a successful message will be shown.

Fig. 6: Data deleted successfully

The html table will be refreshed automatically after 3 seconds of the successful delete operation to reflect the updated state. During the demo, if any error is encountered check whether the backend application is running or not. If the backend application is running check for the application logs to identify the issue. That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we created a react application and understood the delete api call to delete the data from the database with the help of the backend application. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to understand fetch and delete api in a react application.

Download
You can download the full source code of this example here: Delete API in React Application

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button