How to use AJAX in React HTTP GET Request without using Third Party Library

Here I am going to show you how to use AJAX in React HTTP GET request without using Third Party library. To do this I am going to use XMLHttpRequest for fetching data instead of Fetch API (fetch()). AJAX is an acronym that stands for Asynchronous JavaScript and XML.

The Fetch API provides an interface to fetch resources from the server. This Fetch API is similar to the XMLHttpRequest but the new Fetch API provides more powerful and flexible feature set.

The fetch() method takes one mandatory argument, the path to the resource or URL from where you want to fetch data. It returns a Promise that resolves to the Response to that request, whether it is successful or not. You can also optionally pass in an init option as the second argument.

You can build a cross site session using fetch() to receive cross-site cookies. fetch() won’t send cookies, unless you set credentials: 'same-origin'. The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.

If you want you can also use AJAX libraries – Axios, jQuery, Fetch (browser built-in) – in your React application.

You should populate data with AJAX calls in the componentDidMount() lifecycle method, so that you can use setState() to update your component when the data is retrieved.

Prerequisites

Create React JS Application and https://jsonplaceholder.typicode.com/posts

Project Directory

Now I will see step by step how to implement the example using React JS or React framework. The project root directory is reactjs-ajax-without-third-party-library.

AJAX Call in React

Now I am going to use AJAX in React for fetching data from the URL https://jsonplaceholder.typicode.com/posts. I also used the same URL for fetching data but using fetch() method.

Under src folder you will find a file App.js which I am going to edit and put the code required for fetching data from server.

The following code snippets inside componentDidMount() lifecycle method do the job for you. The complete source code you can download later from Source Code section below.

componentDidMount () {
	var request = new XMLHttpRequest();
	
	request.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
	
	request.onload = () => {
		if (request.readyState === 4 && request.status === 200) {
			this.setState({users: JSON.parse(request.responseText)})
		} else {
			//Error
		}
	};
	
	request.onerror = (err) => {
		this.setState({error: err})
	};
	
	request.send();
}

In the above code snippets, I have created an object of type XMLHttpRequest. Then I have used the function open() to pass three parameters. The first parameter is HTTP method, which is GET. The second parameter is the actual URL of the server resource. The third parameter is true or false and it indicates whether you want to fetch data asynchronously or synchronously. I have passed here true to fetch data asynchronously.

Next I am checking when the state is ready (4), which means that the request has been sent to server, server has sent response & browser has finished downloading the content from server. In other words, the AJAX call has been completed. Then I am checking server response status returned is 200.

Finally I set the response data to the users state. I am also parsing the received data as a JSON using JSON.parse() function, otherwise you would get an error saying this.state.users.map is not a function.

I am also handling error using onerror() function. Finally I call the send() function. Once your send() function is called then request is sent to the server. You can also send parameters in the send() function.

Here is the render() function that is used to render or display data on UI (User Interface).

render() {
	if (this.state.error) {
		return <div>Error: {this.state.error.message}</div>;
	} else {
		return (
			<table>
				<thead>
					<tr>
					{
						this.headers.map(function(h) {
							return (
								<th key = {h.key}>{h.label}</th>
							)
						})
					}
					</tr>
				</thead>
				<tbody>
					{
						this.state.users.map(function(item, key) {
							return (
								<tr key = {key}>
								  <td>{item.userId}</td>
								  <td>{item.id}</td>
								  <td>{item.title}</td>
								  <td>{item.body}</td>
								</tr>
							)
						})
					}
				</tbody>
			</table>
		)
	}
}

In this function I have checked whether there is any error during fetching data then show it, otherwise display data in tabular format using HTML table.

Testing the Application

Now execute the command npm start from command line tool on the project’s root. Your application will be deployed on development server and default browser will open URL http://localhost:3000 with data displaying in tabular format as shown in the below image.

ajax in react http get request without using third party library

The image does not show all data but you would see actually many more rows.

That’s all about using AJAX in React HTTP GET request without using third party library.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *