article

Saturday, November 6, 2021

ReactJS How to use AJAX in React HTTP GET Request

ReactJS How to use AJAX in React HTTP GET Request

In this tutorial I'm going to show how to use ajax HTTP GET request without third party library using XMLHttpRequest()

json : https://jsonplaceholder.typicode.com/users

Install bootstrap

npm install react-bootstrap bootstrap@5.1.3

C:\reactdev\myreactdev>npm install react-bootstrap bootstrap@5.1.3

https://react-bootstrap.github.io/getting-started/introduction/

src/index.js
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css'

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
public/index.html
//public/index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>ReactJS </title>
  </head>
  <body>
    <div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React from 'react';

class App extends React.Component {
	
	constructor (props) {
		super(props)
		this.state = {error: null, users: []};
		this.headers = [
			{ key: 'id', label: 'ID' },
			{ key: 'name', label: 'Name' },
			{ key: 'username', label: 'User name' },
			{ key: 'email', label: 'Email' }
		];
	}
	
	componentDidMount () {
		var request = new XMLHttpRequest(); //XMLHttpRequest for fetching data instead of Fetch API (fetch())
		
		request.open('GET', 'https://jsonplaceholder.typicode.com/users', true);
		
		request.onload = () => {
			if (request.readyState === 4 && request.status === 200) {
				this.setState({users: JSON.parse(request.responseText)}) //use setState() to update your component when the data is retrieved.
			} else {
				//Error
			}
		};
		
		request.onerror = (err) => {
			this.setState({error: err})
		};
		
		request.send();
	}
	
	render() {
		if (this.state.error) {
			return <div>Error: {this.state.error.message}</div>;
		} else {
			return (
				<div className="container"><h1>ReactJS How to use AJAX in React HTTP GET Request</h1>
				<table className="table table-bordered table-striped">
					<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.id}</td>
									  <td>{item.name}</td>
									  <td>{item.username}</td>
									  <td>{item.email}</td>
									</tr>
								)
							})
						}
					</tbody>
				</table>
			</div>	
			)
		}
	}
}
export default App;

Related Post