React JS is one of the most popular and mainstream JS framework. Today, we are going to look at a very simple example of how to make an API call with the latest Hook style.
See the following code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const API_URL = 'your url...';
function App() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.get(API_URL);
setData(result.data);
setLoading(false);
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
return (
<div>
{loading ? (
<p>Loading...</p>
) : (
<ul>
{data.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
)}
</div>
);
}
export default App;
The code is a React component that uses Axios to make a GET request to a REST API and display the response data. Here’s a detailed explanation of the code:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
The first two lines import the required libraries and modules: React and Axios.
function App() {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
The App function is a functional React component. The useState hook is used to define two states: data and loading. The data state is initialized with an empty array, and the loading state is initialized with true.
useEffect(() => {
const fetchData = async () => {
try {
const result = await axios.get(API_URL);
setData(result.data);
setLoading(false);
} catch (error) {
console.error(error);
}
};
fetchData();
}, []);
The useEffect hook is used to make the GET request to the API and update the data and loading states. The fetchData function is an asynchronous function that uses Axios to make the GET request to the API. The response data is stored in the result.data object. The setData function is called to update the data state with the response data, and the setLoading function is called to update the loading state to false. If there is an error, it is logged to the console. The useEffect hook is called with an empty dependency array [] to indicate that the effect should only run once, when the component is mounted.
The return statement defines the UI of the component. If the loading state is true, the component displays a “Loading…” message. If the loading state is false, the component maps over the data state and displays a list of post titles. Each list item is given a unique key attribute using the post.id value.