React API Call

React API Call Using Fetch

How can I beat AJAX?

You can use any React API Call library you like with React. Other favorites are Axios, jQuery AJAX, and a built-in browser window.fetch.

Where in the lifecycle should I make an AJAX call?

You must complete the data via AJAX calls in the form of a componentDidMount lifecycle. This is for you to use setState to refresh your item when data is received.

AJAX results are used to set location

The section below shows you how to make an AJAX call to the componentDidMount to fulfill the local component status.

Read Also :  Onclick to Get Current Time in react js

Example 1 : React API call using Fetch with class component

index.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'

export default class Demo extends Component {
  state = {
    value : null
  }

  componentDidMount() {
    fetch('https://reqres.in/api/users?page=2')
    .then(response => response.json())
    .then(json => this.setState({value : json.data}));
  }

  

  render() {
    return (
      <table border="1">
          {
            this.state.value?
            this.state.value.map((data) =>
            <tr>
              <td>{data.id}</td>
              <td>{data.email}</td>
              <td><img src={data.avatar} alt={data.first_name} /></td>
            </tr>
            ):""
          }
      </table>
    )
  }
}

ReactDOM.render(<Demo />,document.getElementById("root"));

Example 2 : React API call using Fetch with functional component

index.js

import React, { Component } from 'react'
import ReactDOM from 'react-dom'
import App from './App'

export default class Demo extends Component {
  render() {
    return (
    <App />
    )
  }
}

ReactDOM.render(<Demo />,document.getElementById("root"));

App.js

import React, { useState, useEffect } from "react";

const App = () => {
  const [tableContent, setTableContent] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/photos")
      .then(response => response.json())
      .then(json => setTableContent(json));
  });

  return (
    <div>
      <table>
        <thead>
          <tr>
            <th>User ID</th>
            <th>Title</th>
          </tr>
        </thead>

        <tbody>
          {tableContent.map(content => {
            return (
              <tr key={content.id}>
                <td>{content.id}</td>
                <td><img src={content.thumbnailUrl} alt={content.thumbnailUrl} /></td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
};

export default App;