Sending an Ajax Request with React

Learn via video courses

Overview

An Ajax (Asynchronous JavaScript and XML) request is a principle that is followed to get, handle, and return the data that is present in the database or a remote server through the backend. When developing large and real-time applications that store data in a database, the data in the application will be updated continuously and we can use Ajax requests to get the data from the database to the react frontend and display it to the users.

How to Make an API Call?

There are different ways to make an API call, but before making an API request we must make sure of the API endpoint link and the type of request that we are going to make.

Let us explore the different ways to make an API call:

We can use the Fetch interface to make API calls and manipulate the response in flexible ways. There are two ways or syntaxes of making a fetch call to the API server,

Fetch with promise chaining

  • The API endpoint is the URL to which the request is to be made.
  • The then block is used to handle the response from the API call.
  • The header is used for the web interface to understand the type of data. A usually seen header is, 'Content-Type': 'application/json' which indicates that we are dealing with JSON datatype.
  • The method determines the type of request. This may be GET, POST etc...
  • The body parameter can be only used if the method of the request is POST or PUT.
  • The catch block is used as an error handling mechanism and is invoked in case of any errors.

The fetch method returns a javascript Promise object. A promise object is an asynchronous object that is used for values that will not be known immediately but will be known in the future. An Ajax with react call will not return the response immediately, but will return the response after some time, therefore the then() block is used to handle the response after the data is given by the server.

Async/Await Syntax

  • The async function allows a method to deal with and return a promise.
  • The await method is used to wait for the complete data to be received and can only be used inside an async function.
  • The json() method is used to read all the incoming data from the response and returns the data completely in JSON format.

The Axios library is one of the widely used open-source libraries for making HTTP requests or API requests. The Axios uses promise objects to handle the response and can automatically transfer the response to JSON data. It also has the functionality to intercept and cancel requests. We can use the npm, bower, or yarn package managers to install the axios library on our local machine. The following commands are used to install the axios package to perform Ajax with react,

The syntax of an axios get request API call is as follows,

  • The axios.get syntax represents that the request made is a GET request.
  • Similar to fetch, we can have a body that will be mostly used when we want to insert values into a database or make complex queries and headers to specify the content type.

Another famous third-party library that is used to make Ajax requests is superagent. Similar to the Axios library, we can download this library using the npm package manager. Unlike axios which doesn't have an in-build retrying feature, superagent has an in-built retry feature to try again if a request fails. The superagent library also handles requests as promises and has an elegant syntax. The syntax for making a superagent POST request is as follows,

Code:

  • The .post denotes that the request is a POST request.
  • The set option is used to set the header for the request.
  • The send is used to set the body for POST and PUT requests.

Jquery is another library that is used for multiple purposes like event handling, animation, and Ajax. An Ajax request made using the jQuery library will have the following syntax,

  • The url is the API endpoint and the type is the method of request.
  • The data is the body sent along with the request and is only applicable to POST/PUT requests.
  • The success function is used to handle the data that is returned from the request. The error function is used to invoke in case of an error during the process.

We can also use the Ajax done() method to handle the data returned by sending the Ajax request and can configure the Ajax settings by using the following syntax,

  • The crossDomain option is used to prevent the most known CORS(Cross-Origin Resource Sharing) problem that works in the server and prevents the request from unknown IP addresses or unknown origins. Setting this option can prevent the blocking of the Ajax request.
  • The async mode must be made to true to handle the call asynchronously using the done function.

Where in the Component Lifecycle should an API Call be Made?

Each component in a react application has a separate lifecycle and has lifecycle methods that run at a particular time during the lifecycle. We can override or alter the functions of this lifecycle method to send an Ajax request with React before the rendering of other components.

  • The states are initialized in the initialization stage in the constructor() function of a component. The initial render occurs after this stage.
  • The mounting stage has the componenentDidMount() function that is invoked just after the component is inserted into the react virtual tree. The Ajax API call in React should be made inside this function.
  • The componentDidUpdate() function is called after a state update is made. If we want to render different data based on the updating of state, we can send an Ajax request with react inside this function.
  • The componentWillUnmount() function is used to clean up any running functions in the component and is called at the last.

where in the component lifecycle should an api call be made

Based on the information, we can say that the initial Ajax with react calls should be made inside the componenentDidMount() function as it is called just after setting of states and we can show all the data received from the API as soon as the browser loads the page.

The lifecycle architecture of the react component is,

Sending an Ajax request with react can also be done using the useEffect() function. The above-discussed method is used if we are dealing with react class components. If we are using react functions, we can use the useEffect() hook. The useEffect() hook can be considered as the combination of the three component functions that we have seen above. The hook can be called just after rendering of state and also after updating of state. The useEffect hook can also be used to clear running functions that are not needed.

A simple useEffect has the following syntax,

  • The function of the hook is invoked at the start of the application and also whenever the state is updated.
  • We send an Ajax request with react inside the useEffect hook and set the response in a state using the useState hook.

The lifecycle of the function-based react architecture will be like this,

  • The state variable stores the data and the useEffect hook gets the data from API and calls the setState function that is used to update the data in the state variable.
  • We can print the data that is stored in the state using the ES6 syntax.

Choosing an HTTP Library to Make API Call

There are multiple API libraries in addition to what has been explained in the above sections. We can choose any of the libraries for sending an Ajax request with React.

The popular choice used by many developers is fetch() and axios(). Fetch is a standard API interface that is supported in all browsers and Axios is an open-source third-party library that has similar functionality to the fetch library.

Making a POST API Request

There are seven methods to request the backend server for fetching or modification of data. The important methods are,

  • The GET method is used to retrieve data from the server or API
  • The POST method is used to send data using the body parameter to the servers and is not mostly used in API calls.
  • The PUT method is similar to the POST method but denotes an update of data.
  • The DELETE method is used to indicate the deletion of data or resources from the server.
  • The PATCH method is used when only small modifications are needed to the data.

A POST request can be easily made with the fetch interface using React JS. The following function illustrates a simple post request made to update the name of the user,

Code:

Explanation

  • The above example illustrates the insertion of user data using a POST request to the server.
  • The arrow syntax of ES6 is used to handle the errors and output at each consecutive step.
  • The JSON.stringify is used to convert the object to json format before sending it to the backend or API.
  • Then the response received is converted into JSON and printed.
  • The catch block is invoked when there is an error and the error is also printed.

A Simple in React Example

Let us consider a simple example in which user data that is present in an API or backend server should be displayed in the front end. We can perform this with the fetch function. The structure of data that will be received from the backend will be as follows,

Code Implementation

  • The constructor is used to create the loading and users state. The loading state will be true till data is received from the backend or API. After data is received the loading state is set to false. This is used to show a loading effect till data is received.
  • The operational operator is used to render the Loading... text till data is received and the loading state changes to false. After data is received data is displayed in a list format.
  • The componentDidMount component has the fetch call that involves sending an Ajax request with react and resolving the data.
  • After the received data is parsed to JSON format, the state is updated using the setState function of the component.
  • After the state is changed a re-render will occur resulting in the displaying of the data that is received from the backend.

Output:

The output shows the data that is fetched from the backend and displayed in the frontend using React.

output of a simple in react example

Conclusion

  • An AJAX request is made to get or handle the data that is present in a remote server or provided by an API.
  • Multiple libraries like fetch, axios, and jquery can be used to perform an Ajax request with react.
  • Each of the libraries handles the data from servers asynchronously and provides it to the front-end.
  • The Ajax request must be made in the compoundDidMount() component in a class component architecture or the useEffect() hook if there is a function-based architecture.
  • There are several methods to make a request and each request deals with a different action that will be made on the data.
  • React uses the state to handle the response of the data from API or backend and renders the data in the frontend application.