React is a popular Javascript library for building user interfaces. React project require interaction with world data. We can access this data by fetching API. In this tutorial we will learn how to fetch data from an API and display data in a table in React js.

API: API is an abbreviated term for Application Programming Interface. It is a set of functions and protocols that allow applications to communicate with each other. An API facilitates the programmers with an efficient way to develop their software programs.
For the data, we need to use an API endpoint to fetch data from it.
The endpoint is:

https://reqres.in/api/products

1. Fetching data using inbuilt fetch API.

We can use the fetch() method to fetch data from the API. We just need to include the endpoint which we want to make our request. Here is an example of fetching data from an API

import { useEffect, useState } from "react";
import "./App.css";
 
function App() {
  const [products, setProducts] = useState([]);
 
  const fetchData = () => {
    fetch("https://reqres.in/api/products")
      .then((res) => res.json())
      .then(({data}) => setProducts(data));
  };
 
  useEffect(() => {
    fetchData();
  }, []);
 
  return (
    <div className="App">
      <table style={{ width: "100%" }}>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Year</th>
            <th>Pantone Value</th>
          </tr>
        </thead>
        <tbody>
          {products.map((product) => (
            <tr>
              <td>{product.id}</td>
              <td>{product.name}</td>
              <td>{product.year}</td>
              <td>{product.pantone_value}</td>
            </tr>
           ))}
        </tbody>
      </table>
    </div>
  );
}
 
export default App;

In the above code. We use useEffect hook, which will be called when the component is mounted. Inside the useEffect hook we are calling fetchData().

In the fetchData function we are making a call to the API and fetching the data and set the data in the state.

The first then is for returning a json object of the result and the second one is for printing. I hope this will help you.

One important thing when you work with api and as well as react you can use console.log (many thing are there but quite familiar with console.log) it helps to what type of data are there you’ll find and this should be helpful for you.

Also Read : Understanding Functional Component and Class Component in React

2. Fetch Data in React using Axios

Axios is a library for making HTTP requests and making API calls. It is based on the Promises. It is easy to use and understand. It is the same as the fetch method of the javascript. We don’t need to convert the response to JSON and use the first .then. Axios directly fetch data and return the JSON object of the result. The advantages of using axios is, it has additional features like canceling the request and retrying the request.Axios is also asynchronou.

First, let’s install the axios using the following command:

npm install axios or, yarn add axios

import axios from "axios";
import { useEffect, useState } from "react";
import "./App.css";
 
function App() {
  const [products, setProducts] = useState([]);
  const usingAxios = () => {
    axios.get("https://reqres.in/api/products").then((response) => {
      setProducts(response.data.data);
    });
  };
 
  useEffect(() => {
    usingAxios();
  }, []);
 
  return (
    <div className="App">
      <table style={{ width: "100%" }}>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Year</th>
            <th>Pantone Value</th>
          </tr>
        </thead>
        <tbody>
          {products.map((product) => (
            <tr>
              <td>{product.id}</td>
              <td>{product.name}</td>
              <td>{product.year}</td>
              <td>{product.pantone_value}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
 
export default App;

3. Fetch Data in React Using async/await syntax

Async/Await enables us to remove our .then() callback and simply get back our asynchronously resolved data. Make sure that you do not use async/await inside the useEffect hook.

import axios from "axios";
import { useEffect, useState } from "react";
import "./App.css";
 
function App() {
  const [products, setProducts] = useState([]);
 
  const usingAxiosAsync = async () => {
    const response = await axios.get("https://reqres.in/api/products");
    setProducts(response.data.data);
  };
 
  useEffect(() => {
    usingAxiosAsync();
  }, []);
 
  return (
    <div className="App">
      <table style={{ width: "100%" }}>
        <thead>
          <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Year</th>
            <th>Pantone Value</th>
          </tr>
        </thead>
        <tbody>
          {products.map((product) => (
            <tr>
              <td>{product.id}</td>
              <td>{product.name}</td>
              <td>{product.year}</td>
              <td>{product.pantone_value}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
 
export default App;

The output of the above code is

Fetch Data From API React

One more thing, when we run the code in browser we get warning like this

Fetch data from API in react error

It simply means we didn’t add unique key so we will add key in our code, here is example code

<tbody>
    {products.map((product) => (
        <tr key={product.id}>
        <td>{product.id}</td>
        <td>{product.name}</td>
        <td>{product.year}</td>
         <td>{product.pantone_value}</td>
      </tr>
     ))}
 </tbody>

Leave Your Comment