HTTP And React

Introduction

 
In the previous article, we learned about the concept of Render Props and Context in React. In this article, we will dive into some advanced concepts of React, like HTTP and usage of the GET and POST methods for data retrieval.
 

Basics of HTTP and React

 
So far, we have learned about the basics of React and how props and state are used. Now, we will learn how React makes API calls fetch data and display in the browser. As React is just a library for the user interface, it only knows about Props and State so here, HTTP comes into the picture.
 
To fetch data in React, there are many HTTP libraries available like - Apollo, Axios, Relay Modern, Request, and Superagent. In this article, we are going to use Axios library.
 
First of all, we will create a new React app using the following command. 
  1. npx create-react-app http-react  
The app is created now. Now, go to your newly created folder and install Axios to use it further in our application.
  1. npm install axios  
After the command is executed successfully, we will see in the package.json file that the dependencies are updated.
 
HTTP and React
 
Now, we will see how we can fetch data and display in the browser.
 

HTTP GET

 
Here, we are using an online API to fetch data from it instead of creating our own API. We are using https://reqres.in/ to test our application.
 
Create a component named DisplayList.js.
  1. import React, { Component } from 'react'  
  2. export class DisplayList extends Component {  
  3.   render() {  
  4.     return (  
  5.       <div>  
  6.         List of Users  
  7. </div>  
  8.     )  
  9.   }  
  10. }  
  11. export default DisplayList  
And include this component in App.js.
  1. import React from 'react';  
  2. import logo from './logo.svg';  
  3. import './App.css';  
  4. import DisplayList from './components/DisplayList'  
  5. function App() {  
  6.   return (  
  7.     <div className="App">  
  8.       <DisplayList></DisplayList>  
  9.     </div>  
  10.   );  
  11. }  
  12. export default App;  
It will display the output as below.
 
HTTP and React
 
Now, we will fetch data from library using Axios. For that, first, we need to import the axios library.
  1. import axios from 'axios'  
Now, to store the data that we get from API, we will create an empty array in state.
  1. this.state = {  
  2.      Users:[]  
  3. }  
Now, we will call the API and store the data in our array in componentDidMount() lifecycle method. This is executed when the component mounts for the first time and it is called only once.
 
So, the component will go like below.
  1. import React, { Component } from 'react'  
  2. import axios from 'axios'  
  3.   
  4. const error ={    
  5.     color: 'red',    
  6.     fontWeight:'bold',    
  7.     fontSize:'14'    
  8. }    
  9.   
  10. export class DisplayList extends Component {  
  11.     constructor(props) {  
  12.         super(props)  
  13.       
  14.         this.state = {  
  15.             users:[],  
  16.              errorMessage:""  
  17.         }  
  18.     }  
  19.       
  20.     componentDidMount(){  
  21.         axios.get('https://reqres.in/api/users/')  
  22.         .then(response => {  
  23.             console.log(response.data.data)  
  24.             this.setState({  
  25.                 users:response.data.data  
  26.             })  
  27.         })  
  28.         .catch(error =>{  
  29.             this.setState({  
  30.                 errorMessage:"Error fetching data"  
  31.             })  
  32.         })  
  33.     }  
  34.     render() {  
  35.         const {users,errorMessage} = this.state  
  36.         console.log(users.length)  
  37.         return (  
  38.             <div>  
  39.                 List of Users  
  40.                 {  
  41.                     users.length?  
  42.                     users.map(user=> <div key={user.id}><img src={user.avatar} alt={user.first_name}/>{user.first_name + " "+ user.last_name}</div>):  
  43.                     null                      
  44.                 }  
  45.                 {errorMessage ? <div style={error}>{errorMessage}</div> : null}  
  46.             </div>  
  47.         )  
  48.     }  
  49. }  
  50.   
  51. export default DisplayList  
The output will be as below.
 
HTTP and React
 
In the above, componentDidMount() will be called once the component is mounted, so it will display a list of users from provided API. If the API is incorrect or does not return output, then the error message will be displayed.
HTTP and React
 
Next, we will be learning about HTTP Post.
 

HTTP POST

 
Like HTTP Get, we use Axios Post method to send the data to the API we use.
 
Let’s see a demo.
  1. import React, { Component } from 'react'  
  2. import axios from 'axios'  
  3.   
  4. class UserForm extends Component {  
  5.     constructor(props) {  
  6.         super(props)  
  7.   
  8.         this.state = {            
  9.             first_name: "",  
  10.             last_name: "",  
  11.             email: ""  
  12.         }  
  13.     }  
  14.   
  15.     onChangeHandler = (e) => {  
  16.         this.setState({ [e.target.name]: e.target.value })         
  17.     }  
  18.   
  19.     onSubmitHandler = (e) => {  
  20.         e.preventDefault();  
  21.         console.log(this.state)  
  22.         axios.post('https://reqres.in/api/users/',this.state)  
  23.         .then(response=>{  
  24.             console.log(response)  
  25.         })  
  26.         .catch(error => {  
  27.             console.log(error)  
  28.         })  
  29.     }  
  30.   
  31.     render() {  
  32.         const { first_name, last_name, email } = this.state  
  33.         return (  
  34.             <div>  
  35.                 <form onSubmit={this.onSubmitHandler}>                     
  36.                     <div>  
  37.                         Email : <input type="text" name="email" value={email} onChange={this.onChangeHandler} />  
  38.                     </div>  
  39.                     <div>  
  40.                         First Name : <input type="text" name="first_name" value={first_name} onChange={this.onChangeHandler} />  
  41.                     </div>  
  42.                     <div>  
  43.                         Last Name : <input type="text" name="last_name" value={last_name} onChange={this.onChangeHandler} />  
  44.                     </div>  
  45.                     <button type="submit">Submit</button>  
  46.                 </form>  
  47.             </div>  
  48.         )  
  49.     }  
  50. }  
  51.   
  52. export default UserForm  

Let us include UserForm component in App.js.

  1. import React from 'react';  
  2. import './App.css';  
  3. import UserForm from './components/UserForm'  
  4.   
  5. function App() {  
  6.   return (  
  7.     <div className="App">        
  8.       <UserForm></UserForm>  
  9.     </div>  
  10.   );  
  11. }  
  12.   
  13. export default App;  
The output will be displayed as below.
 
HTTP and React
 
We can also use PUT, DELETE function in the same way.
 

FAQs

 
How can AJAX call be made in React?
 
There are many AJAX libraries available you can use with React. Some popular libraries are Axios, jQuery Ajax, and Window.fetch which is browser built-in.
 
Where AJAX calls should be made in Component lifecycle?
 
The calls should be made in componentDidMount() method as this method allows setState() to update your component after retrieval of data.
 

Summary

 
In this article, we have learned how React and Web server connect to each other to pass data and how HTTP Get and HTTP Post work.
 
You can download the source code attached. With this article, I've finished the basics of React. Now, I will move on to  Advanced React which will have React Hooks and how hooks work in React. If you have any confusion or suggestions, please do comment.
Author
Priyanka Jain
0 9.6k 894.8k
Next » Introduction To React Hooks