In React, you can make API requests using various methods, but one common approach is to use the fetch
API or third-party libraries like axios
. I will provide you with an example of how to make an API request using both fetch
and axios
.
If you want to make a GET API request to retrieve some data from a Server.
Here’s follow some methods that you can do it:
Method – 1 Using the fetch API:
import React, { useState, useEffect } from 'react';
function UserComponent() {
const [data, setData] = useState([]);
useEffect(() => {
fetch('https://api.mydomain.com/Endpoint') // Replace with your API endpoint
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Unable to fetch data from API:', error));
}, []);
return (
<div>
<h1> Data Receivied from API</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default UserComponent;
JavaScriptAbove method we used the fetch method which is the default method provided by javascript, you don’t need to install any third-party package for this.
Method – 2 Using Axis Library
First, you need to install the axis package using npm, please use the below command in your terminal to install the axis on your react application.
npm install axios
BashNow it’s time to import the axis package to your react component.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function UserComponent() {
const [data, setData] = useState([]);
useEffect(() => {
axios.get('https://api.mydomain.com/Endpoint') // Replace with your API endpoint
.then(response => setData(response.data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
<h1> Data Receivied from API</h1>
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
}
export default UserComponent;
JavaScriptBoth above examples show how can you make a GET request and update the component’s state with the fetched data from the server, Remember we used a dummy API use you need to replace the API endpoint with the actual endpoint.
React Show a Loading Progress Bar in API Call
Happy Coding โบ๏ธ
No Comments
Leave a comment Cancel