REST API at http://jsonplaceholder.typicode.com/users for testing
The componentDidMount() life-cycle hook. This is executed when your React component is inserted/mounted in the DOM.
Installing the Axios Client
$ npm install axios
C:\reactdev\myreactdev>npm install axios
https://axios-http.com/docs/intro
https://github.com/axios/axios
https://github.com/axios/axios
//src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
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>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div id="root"></div>
</body>
</html>
src/App.js
//src/App.js
import React, { Component } from 'react';
import axios from 'axios';
const API_URL = 'http://jsonplaceholder.typicode.com';
class App extends Component {
state = {
users: []
}
//https://jsonplaceholder.typicode.com/users
componentDidMount() {
const url = `${API_URL}/users/`; //alt + 96 = `
axios.get(url).then(response => response.data)
.then((data) => {
this.setState({ users: data })
console.log(this.state.users)
})
}
render() {
return (
<div className="container" style={{padding: 20}}>
<div className="col-xs-8">
<h1>ReactJS Axios JSON REST API</h1>
<table className="table table-striped">
<thead className="thead-light ">
<th>Name</th>
<th>User Name</th>
<th>Email</th>
<th>Website</th>
</thead>
<tbody>
{this.state.users.map((user) => (
<tr>
<td>{user.name}</td>
<td>{user.username}</td>
<td>{user.email}</td>
<td>{user.website}</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
}
export default App;
