How to Display API Data Using Axios 馃殌 with React 鈽革笍

How to Display API Data Using Axios 馃殌 with React 鈽革笍

To call an API and display the data in a React JS application using either the Fetch API or Axios, you can follow these steps:

  1. Import the necessary libraries: For Fetch API, you don't need to install any library as it is a built-in function in modern browsers. However, if you prefer to use Axios, you need to install it first using npm or yarn.
// For Fetch API
import React, { useState, useEffect } from 'react';

// For Axios
import React, { useState, useEffect } from 'react';
import axios from 'axios';
  1. Create a state to store the API response:
const [data, setData] = useState([]);
  1. Use the Fetch API or Axios to fetch the data from the API endpoint:

For Fetch API:

useEffect(() => {
  fetch('https://api.example.com/data')
    .then(response => response.json())
    .then(data => setData(data))
}, []);

For Axios:

useEffect(() => {
  axios.get('https://api.example.com/data')
    .then(response => setData(response.data))
    .catch(error => console.log(error))
}, []);
  1. Display the data in the component:
return (
  <div>
    {data.map(item => (
      <div key={item.id}>
        <h2>{item.title}</h2>
        <p>{item.body}</p>
      </div>
    ))}
  </div>
);

This code assumes that the API response is an array of objects with id, title, and body properties. You will need to modify it according to your API response structure.