Last updated on July 7, 2023
To make an HTTP request in React.js, you can use the built-in fetch
function or third-party libraries like Axios or the axios
adapter for fetch
. Here’s an example of using the fetch
function to make an HTTP GET request in React:
import React, { useEffect, useState } from 'react';
const MyComponent = () => {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch('https://api.example.com/data');
const jsonData = await response.json();
setData(jsonData);
} catch (error) {
console.error('Error:', error);
}
};
fetchData();
}, []);
return (
<div>
{data ? (
<ul>
{data.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
) : (
<p>Loading data...</p>
)}
</div>
);
};
export default MyComponent;
In the example above:
- We define a functional component called
MyComponent
. - Inside the component, we use the
useState
hook to define a state variabledata
and a setter functionsetData
to store the fetched data. - We use the
useEffect
hook to fetch data when the component mounts (using an empty dependency array[]
). - In the
fetchData
function, we usefetch
to make an HTTP GET request to'https://api.example.com/data'
. - We parse the response data using
response.json()
. - The parsed JSON data is then set to the
data
state variable usingsetData
. - We conditionally render the data in the component. If the data is available, we render a list of items. Otherwise, we display a loading message.
Note that this is a basic example, and you may need to handle error scenarios, additional HTTP methods, headers, and other options based on your specific requirements.