In this article, we will see how to make API calls using the functional components.
Importing required libraries:
There are some libraries available and by using those we can make API requests in react. For this, we can use the ‘axios‘ module which is a popular choice for making API calls in React.
import axios from 'axios';
State to hold the API response
After making an API request, we will get a response from the server. To display the data we receive from the API, we need to create a state that will hold the response. We can use the ‘useState’ hook to create the state.
const [data, setData] = useState(null);
Make the API call
Finally, using the axios we perform a GET request to the end point. We use the ‘useEffect‘ hook to perform the API call when the component mounts.
To make the API call, we will use the ‘axios’ module to perform a GET request to the API endpoint. We can use the ‘useEffect’ hook to perform the API call when the component mounts. This ensures that the API call is made only once when the component is rendered for the first time.
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(response => {
setData(response.data);
})
.catch(error => {
console.log(error);
});
}, []);
In the code above, we are making a GET request to the ‘https://jsonplaceholder.typicode.com/users‘ endpoint. Once the response is received, we update the state with the data received from the API. If an error occurs during the request, we log it to the console.
Render the API response
As we have received the response from the API and stored it in the state variable,now we need to render this data in our component. For this, we use the conditional rendering to check if the data exists before rendering it.
return (
<div>
{data ? (
<ul>
{data.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
) : (
<p>Loading...</p>
)}
</div>
);
In the above example, we are checking if the ‘data‘ state exists before rendering it. If the data exists, we render a list of users fetched from the API. Otherwise, we display a ‘Loading…’ message until the API response is received.