The goal of this tutorial is to guide you on how to fetch data from an API in a React application using two popular methods: Fetch and Axios.
Fetch is a built-in browser API for making HTTP requests. It's promise-based, and it's a great option for simple requests. However, it's not supported in Internet Explorer.
Axios is a popular, promise-based HTTP client that sports an easy-to-use API and can be used in both the browser and Node.js. It has a number of advantages over Fetch, such as the ability to automatically transform JSON data.
// Import react and useState, useEffect hooks
import React, { useState, useEffect } from 'react';
const FetchExample = () => {
const [data, setData] = useState([]);
// Use useEffect to call the API once the component has mounted
useEffect(() => {
fetch('https://api.example.com/items')
.then(response => response.json())
.then(data => setData(data));
}, []);
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
};
export default FetchExample;
In this example, we are fetching data from 'https://api.example.com/items' URL. The fetched data is then converted to JSON format using response.json()
. The JSON data is saved in the data
state variable using setData
function.
// Import react, useState, useEffect hooks, and axios
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const AxiosExample = () => {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('https://api.example.com/items')
.then(response => {
setData(response.data);
})
.catch(error => console.error(`Error: ${error}`));
}, []);
return (
<div>
{data.map(item => (
<p key={item.id}>{item.name}</p>
))}
</div>
);
};
export default AxiosExample;
In the Axios example, we are doing the same thing but with the Axios library. The advantage here is that Axios automatically converts the response data into JSON, so we don't have to call .json()
as with fetch. Also, Axios provides a simple way to catch and handle errors.