article

Tuesday, October 19, 2021

ReactJS How to call API - fetch then json

ReactJS How to call API - fetch then json

In this tutorial I will show show how to fetch data via API call in React JS.
https://reqres.in/api/users/

src/index.js
//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 from 'react';
import './App.css';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userList: [],
      loading: false
    }
    this.getUserList = this.getUserList.bind(this);
  }

  getUserList() {
    this.setState({ loading: true });
    fetch('https://reqres.in/api/users/?per_page=5&page=2')
      .then(res => res.json())
      .then(res => {
        setTimeout(() => {
          this.setState({ loading: false, userList: res.data });
        }, 2000);
      })
  }

  render() {
    const { userList, loading } = this.state;

    return (
      <div className="container App">

        <h4 className="d-inline-block">ReactJS How to call API - fetch then json</h4>
        <button className="btn btn-info float-right" onClick={this.getUserList} disabled={loading}>{loading ? 'Loading...' : 'Show User List'}</button>
        <div className="clearfix"></div>

        <table className="table table-striped">
          <thead className="thead-light ">
            <th>First Name</th>
            <th>Last Name</th>
            <th>Email</th>
            <th>Avatar</th>
          </thead>
          <tbody>
            {userList.map(row => <tr>
              <td>{row.first_name}</td>
              <td>{row.last_name}</td>
              <td>{row.email}</td>
              <td><img src={row.avatar} width="50" height="50" /></td>
            </tr>)}
            {userList.length == 0 && <tr>
              <td className="text-center" colSpan="4">
                <b>No data found to display.</b>
              </td>
            </tr>}
          </tbody>
        </table>

      </div>
    );
  }
}

export default App;
src/App.css
.App {
  padding:20px;
}

Related Post