There are several ways to manage multiple API calls in React, depending on your specific use case and requirements. Here are a few common approaches:
import React, { useState, useEffect } from 'react';
const MyComponent = () => {
const [data1, setData1] = useState(null);
const [data2, setData2] = useState(null);
useEffect(() => {
const fetchData = async () => {
const [response1, response2] = await Promise.all([
fetch('API_ENDPOINT_1'),
fetch('API_ENDPOINT_2'),
]);
const data1 = await response1.json();
const data2 = await response2.json();
setData1(data1);
setData2(data2);
};
fetchData();
}, []);
return (
<div>
{/* render data1 and data2 */}
</div>
);
};
export default MyComponent;
import React, { useState } from 'react';
const MyComponent = () => {
const [data1, setData1] = useState(null);
const [data2, setData2] = useState(null);
const fetchData = async () => {
const response1 = await fetch('API_ENDPOINT_1');
const response2 = await fetch('API_ENDPOINT_2');
const data1 = await response1.json();
const data2 = await response2.json();
setData1(data1);
setData2(data2);
};
useEffect(() => {
fetchData();
}, []);
return (
<div>
{/* render data1 and data2 */}
</div>
);
};
export default MyComponent;
Overall, the best approach for managing multiple API calls in React depends on the complexity of your application and your specific requirements. Consider the trade-offs between simplicity, performance, and flexibility when choosing an approach.