Skip to content

Instantly share code, notes, and snippets.

@giangmd
Created December 18, 2019 08:20
Show Gist options
  • Save giangmd/b22d521354c5782bfec2463a31b58e98 to your computer and use it in GitHub Desktop.
Save giangmd/b22d521354c5782bfec2463a31b58e98 to your computer and use it in GitHub Desktop.
Reactjs Get Data from API
import React, { Component } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
class App extends Component {
constructor() {
super();
this.state = {
users: []
}
}
async componentDidMount() {
await fetch('http://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then((data) => {
this.setState({ users: data })
})
.catch(console.log)
}
renderUsers = () => {
let users = this.state.users.map((data, index) =>
<tr key={data.id}>
<td>{data.id}</td>
<td>{data.name}</td>
<td>{data.email}</td>
<td>{data.website}</td>
</tr>
);
return users;
}
render() {
return (
<div className="App">
<div className="container">
<h1 className="text-center">Users List</h1>
<table className="table">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Email</th>
<th>Website</th>
</tr>
</thead>
<tbody>
{this.renderUsers()}
</tbody>
</table>
</div>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment