How to make a REST API call in React


This article provides an overview of making a REST API call in the React library using JavaScript Fetch API. The readers of this article must have some prior knowledge of using React library for creating user interfaces. It uses functional component approach and controlled form for building component-based design. This article demonstrates use case for posting blog content in the MongoDB database as an example. 

Functional Components

Functional components are written using JavaScript function syntax in React. When compared with class based components, they use much less code and are easier to undersand. Class components follow ECMAScript 6 (ES6) class based syntax for defining components and are relatively complex due to the following reasons.

  • Each class component extends from the React.Component class. Functional components are simple JavaScript functions and they don't need to be subclass of the React.Component class.
  • Class component must define render() function, failing to which will result in an error. Functional components don't need any render() function in their body.
  • Class component must define constructor if it has to initialise the state variables. Functional components use useState() hook for state management. 

Controlled Forms

Both class and functional components can use controlled or uncontrolled forms for collecting user information. Controlled forms have advantage over uncontrolled forms because component state handles data from HTML form elements. It acts as "the single source of truth" within these components. Whenever data in any of the HTML input elements changes, the state corresponding to that input element gets updated. Uncontrolled forms use the traditional approach of storing the data in HTML DOM elements rather than components. They need ref attribute inside individual input elements to reterieve data from the DOM.

In this tutorial, we are using functional components with controlled forms for implementing the use case of posting the blog content to the MongoDB database using a REST API call.

REST API call in React

We assume that a REST API having endpoints for inserting, updating and deleting blog contents is already designed and published. The subsequent code-snippets will implement a React component to access blog posting endpoint and send data for insertion into the MongoDB database. 

The HTML form to collect user data contains sample fields for title, snippet and body of the blog.

Post Blog

The summary of the JavaScript code written in React component PostBlog() is given below:

  • The React component PostBlog() is a functional component and is defined using a JavaScript function definition syntax.
  • It uses useState() hook and JavaScript destructuring assignment approach for creating state variables for storing blog content. The state variables created for this example are title, snippet and body.
  • The value attribute within each HTML input element holds the updated value of the state variable. 
  • The JavaScript onChange() event inside HTML input elements updates values of state variables whenever user changes data in any of the input element.
import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import './PostBlog.css'

function PostBlog() {

    const [title, setTitle] = useState('')
    const [snippet, setSnippet] = useState('')
    const [body, setBody] = useState('')

    const navigate = useNavigate()

    function addBlog(event) {

        event.preventDefault();

        var blog = { title, snippet, body }
        console.log(blog)

        fetch("http://localhost:3001/blogs", {
            method: "POST",
            body: JSON.stringify(blog),
            headers: {
                "Content-Type": "application/json"
            }
        }).then(function (response) {
            if (response.ok) {
                navigate('/ViewBlogs')
            } else {
                var error = new Error(response.statusText)
                error.response = response
                throw error
            }
        })
    }

    return (
      <div align="center"> <h1>Post New Blog</h1>
       <div class="create-blog content">
        <form> 
         <table>
          <tr>
           <td><label>Enter Title</label></td>
           <td><input type="text" value={title} onChange={(e) => { setTitle(e.target.value) }} placeholder="Enter Blog Title here ...." /></td>
          </tr>  
          <tr>
           <td><label>Blog Snippet</label></td>
           <td><input type="text" value={snippet} onChange={(e) => { setSnippet(e.target.value) }} placeholder="Enter Blog Snippet here ...." /></td>
          </tr>  
          <tr>
           <td><label>Blog Body</label></td>
           <td><textarea value={body} onChange={(e) => { setBody(e.target.value) }} placeholder="Enter Blog Body here ...."></textarea></td>
          </tr>  
          <tr>
           <td colspan="2" align="center">
            <button type="submit" value="Submit" onClick={addBlog}>Submit</button>
           </td> 
          </tr>
         </table> 
       </form>
      </div> 
     </div >
    )}

export default PostBlog
  • When user clicks on the submit button, the JavaScript function addBlog() is invoked. It reads values from the state variables and constructs a JavaScript object 'blog'
  • The fetch API makes an asynchronous HTTP Request at REST API endpoint http://localhost:3001/blogs. It uses POST method and value of Content-Type header is set to application/json. The blog JavaScript object is converted into a string using JSON.stringify() method and is sent inside body of the HTTP Request packet.
  • The fetch API returns promise object which is handled by defining an anonymous callback function as first argument of the promise.then() method. If the promise is fulfilled, the system will navigate to the ViewBlogs component which will display the recently added blog in the list of blogs published on the Web page.

Conclusion

This article has laid-down a roadmap for developers using React for component-based UI design. It takes code-snippets from the blog application project to demonstrate the sample implementation which consumes REST APIs for accessing external resources. This article may also help those developers who are building Decentralised Apps (dAPPs) as JavaScript is also used as a front-end development language in the Web3 technology stack.

How do you rate this article?

3



Component-based Front-end Frameworks
Component-based Front-end Frameworks

This blog covers programming use cases to demonstrate the implementation of component-based frameworks and libraries such as Angular, React etc for front-end Web development. The code snippets are sample implementations from different projects built as part of the learning exercise.

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.