Apollo Fredrick
Posted on January 23, 2024
React is a JavaScript library for building user interfaces. Often you will want to fetch data from an API and display it in your React application.
Axios is a promise-based HTTP client that makes it easy to fetch data from APIs.
In this tutorial I will show you the simplest way to fetch API data and display it in your website.
Prerequisites
You should have a basic knowledge of React
Install Axios
Install Axios in your project folder using the following command:
npm install axios
Import Axios
Import Axios in the component which you want to make API calls in as shown below:
import React, { useEffect, useState } from 'react';
import axios from 'axios';
Making a GET Request
To make a GET request, use the following code:
axios.get(url)
.then(response => {
// Handle the successful response here
console.log(response.data);
})
.catch(error => {
// Handle errors here
console.error('Error fetching data:', error);
});
Handling Asynchronous Operations
To handle asynchronous functions we use 'async/await' since API calls are asynchronous operations and React ensures that the UI remains responsive during these calls:
const fetchData = async() =>{
try {
const response = await axios.get(url)
setData([response.data])
} catch (error) {
console.log(error)
}
}
fetchData()
Integrate with React Components
Integrate your knowledge of data fetching in your React components as shown below:
import axios from 'axios'
import React, {useState, useEffect} from 'react'
const App = () => {
const [data, setData] = useState([])
const url = "https://api.chucknorris.io/jokes/random"
useEffect(() => {
const fetchData = async() =>{
try {
const response = await axios.get(url)
setData([response.data.value])
} catch (error) {
console.log(error)
}
}
fetchData()
}, [])
return (
<ul>
{data.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
)
}
export default App
We use the useEffect hook to call the API when the component mounts.
Axios makes the Get request and returns a promise. When the promise resolves, we set the state using setData.
We finally use the map function to loop the data and display it on the page.
Remove React.StrictMode in your index.js file(If you are using Create-React-App) or main.js file(If you are using Vite) to prevent the useEfect hook from running twice.
Refresh the page to get more Chuck Norris jokes.
Posted on January 23, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.