Requirement
Every application should be able to fetch data from server or some other end point, send data to the server for saving it to the database or other processing, communicate between client and server for monitoring or some other purpose. Communication between a web application running on a web browser and remote server is possible only through HTTP requests. Thus, support for HTTP requests is an integral part of any application.
HTTP requests in react
React applications support integration of HTTP requests using a commonly used third party library axios. For using the features of this library, you need to install it using command npm install axios. This command should be executed on the command prompt in Windows(or terminal in Mac and linux) system. Refer below screenshot.
When axios library is integrated, you can easily use it to make Ajax requests from your react application.
This library can be used in a react or any other web application that utilizes npm.
About axios
Axios library supports all types of HTTP requests, that is, GET, POST, PUT, DELETE, HEAD and PATCH. It is a promise based library meaning it uses promises to support asynchronous operations.
Asynchronous means non-blocking. Suppose you are reading a file from disk. A synchronous operation would block the application till the file is read while an asynchronous operation will allow the application to move forward while the file is being read.
A promise in asynchronous operation represents the result of the operation. In file reading example, a promise will contain the contents of the file after it is completely read. Using promises has the advantage that when the operation completes, the control is transferred to the callback function automatically where the result can be processed. Example,
axios.get('https://tutorials.codippa.com/http-request').then(response => { // called when the response is available console.log(response); }) // other code
Above snippet executes a GET request using axios which fetches data from the server. Obviously, this is going to take some time. The application does not block but continues executing the code after the request is made. As soon as the response is available, then
block is executed where you can do further processing with the response. Here we are just logging it to the console. This is the advantage of using Promises. Further details about axios are available here.
Using axios in react
Once axios package is installed in the application, we can straightaway start using it to make HTTP requests. For using axios, we need to import it in the component where we want to use it. For fetching data, we will be using a dummy datasource URL https://jsonplaceholder.typicode.com/users. This will return an array of objects each having some properties, we will be accessing their name property.
As we learned in the component lifecycle section, any initialization should be performed in the componentDidMount
lifecycle method since we can easily modify the state
object in this method. Thus, GET request for fetching data will be written here. Once the response is fetched, we will be displaying the list of users in the render
method. Code is given below followed by an explanation. Copy and paste this code in the index.js file of your react application and see the result for a better understanding.
import React, {Component} from 'react'; import ReactDOM from 'react-dom'; import axios from 'axios'; // User component const User = (props) => { return <div>{props.name}</div> } // create a router component class HTTPRequestComponent extends Component { state = { users: [] } componentDidMount() { // GET request using axios axios.get('https://jsonplaceholder.typicode.com/users').then(response => { // populate users object with response this.setState({users:response.data}); }) } render(){ // check is users has been populated if(this.state.users) { const users = this.state.users.map(user => { return <User name = {user.name}/> }); return <div>{users}</div> } else { // show loading message till response is received return <div>Loading...</div> } } } // attach ReactDOM.render(<HTTPRequestComponent />, document.getElementById('root'));
As a first step, axios is imported into the component and state
object is initialized with the users
array. This array is initially empty but will hold the response once it is fetched from the server.
In the componentDidMount
method, we make an HTTP GET request using axios supplying the URL. We cannot execute the GET request in the render
method since fetching the response from the server might take some time and javascript will not wait for the response to return and thus, render
method will complete while the response is being fetched. So nothing will be rendered on the screen.
Once the response is fetched, the callback function is executed which populates the response into the users
array of state
object using setState
method. Note that the response from the GET request contains a data property which contains the actual records. You can check this by writing console.log(response);
.
Since we are modifying the state
object in componentDidMount
method, it causes the render
method to be executed again. In the render
method, we first check if the users
array of state
object has been populated. If it is, then we iterate over the array using javascript’s map
method and return a user component with its name
property evaluated to the name
of each user fetched from the server. If the users
array is not populated, we display a Loading… message. Note that in the absence of if condition, you might get an error.
Also, note that we created a User component as a functional component which receives a props
object. props
object contains a name property which we have set in the render
method.
Similar to the GET request, we can also execute all other HTTP requests using axios. That is all in this section.