How to make a REST API call in React

Do repost and rate:

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 prioir knowledge of using library for creating user interfaces. It uses functional component approach and controlled form for building component-based design. This article demostrates 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 component must define function, failing to which will result in an error. Functional components don't need any 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 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.

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.
  • useState() hook and JavaScript destructuring assignment approach for creating state variables for storing blog content. The state variables created for this example are
  • 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.
 useState  useNavigate 'react-router-dom''./PostBlog.css'functionPostBlog setTitleuseState setSnippetuseState setBodyuseState navigate useNavigatefunction        eventpreventDefault                console        "http://localhost:3001/blogs"            method            bodystringify            headers                "Content-Type""application/json"                    functionresponse            response                '/ViewBlogs'                            responsestatusText                errorresponse  response                 error                    div alignPost New Blog       "create-blog content"                                       Enter Title           input type onChange placeholder"Enter Blog Title here ...."                                 Blog Snippet           input type onChangesetSnippet placeholder"Enter Blog Snippet here ...."                                 Blog Body           textarea value onChange placeholder"Enter Blog Body here ...."                                 td colspan            button type"submit""Submit" onClick                                        PostBlog
  • When user clicks on the button, the JavaScript function addBlog() is invoked. It reads values from the state variables and constructs a JavaScript object
  • fetch API makes an asynchronous HTTP Request at REST API endpoint http://localhost:3001/blogs. It uses method and value of Content-Type header is set to application/json JavaScript object is converted into a string using JSON.stringify() method and is sent inside body of the HTTP Request packet.
  • fetch API object which is handled by defining an anonymous callback function as first argument of the promise.then() method. If the is fulfilled, the system will 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

Regulation and Society adoption

Ждем новостей

Нет новых страниц

Следующая новость