React.js

Fetch and Post API in React Application

Welcome readers, in this tutorial, we will implement a fetch and post 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 –

Angular React
Complete framework Library
Object-oriented programming Extension to the javascript library and its internal architecture is based on jsx
Based on the model view controller and real document object model Based 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 get-and-post-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 post 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 the backend project

To perform the fetch and post API call in react application I will be using a separate node.js application that exposes the get endpoint to fetch the users from the PostgreSQL database. Since the node.js 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 create an html form interface that will take the user input. On submitting the form the data will be sent to the backend application endpoint (i.e. /create) running on the nodejs server at port number – 9500 to save it in the database. Remove the existing changes from the app.js file and replace them with the ones below.

App.js

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

function App() {
  const create = "http://localhost:9500/create";

  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [age, setAge] = useState("");

  let [status, setStatus] = useState(undefined);
  let [state, setState] = useState(undefined);

  function saveUser() {
    // console.log(name, email, age);
    let data = { name, email, age };

    // input form validation
    if (!data.name || !data.email || !data.age) {
      setState({ error: "field cannot be blank or empty" });
      return;
    }

    let requestOptions = {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(data),
    };

    fetch(create, requestOptions)
      .then((result) => {
        // handle response
        // console.log("data created", result);
        setStatus({ type: "success", message: result.statusText });

        // Todo - add the fetch api to show response
      })
      .catch((err) => {
        // handle error
        // console.log("error occurred!", err);
        setStatus({ type: "error", message: err.message });
      });
  }

  return (
    <div className="App">
      <h1>React crud - Fetch POST example</h1>
      <input
        type="text"
        name="name"
        value={name}
        onChange={(e) => {
          setState("");
          setName(e.target.value);
        }}
        placeholder="Enter name"
      />
      <br /> <br />
      <input
        type="email"
        name="email"
        value={email}
        onChange={(e) => {
          setState("");
          setEmail(e.target.value);
        }}
        placeholder="Enter email"
      />
      <br /> <br />
      <input
        type="number"
        name="age"
        value={age}
        onChange={(e) => {
          setState("");
          setAge(e.target.value);
        }}
        placeholder="Enter age"
      />
      <br /> <br />
      <button type="button" onClick={saveUser}>
        Create new user
      </button>
      <div id="note">
        <small>
          Get all users can be fetched by clicking
          <a
            id="getall-users"
            href="http://localhost:9500/all"
            target="_blank"
            rel="noreferrer"
          >
            here
          </a>
        </small>
      </div>
      <div id="validations">
        {state?.error !== undefined && <p>{state?.error}</p>}
        {status?.type === "success" && <p>{status?.message}</p>}
        {status?.type === "error" && <p>{status?.message}</p>}
      </div>
    </div>
  );
}

export default App;

3. Run the setup

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

Fill in the user form and click on submit. If the data will be successfully inserted into the db a success message will be shown otherwise the error message.

Fig. 5: Data inserted successfully

Once the success message is shown hit the backend application /all endpoint to confirm whether the data was successfully inserted into the db or not.

Backend application endpoint

// get all users endpoint
// http://localhost:9500/all

You can also click on the hyperlink showing on the ui to fetch the data. 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 post api call to add new data into 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 post api in a react application.

Download
You can download the full source code of this example here: fetch and post 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
Inline Feedbacks
View all comments
Back to top button