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:
- 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';
- Create a state to store the API response:
const [data, setData] = useState([]);
- 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))
}, []);
- 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.
聽