FRONTEND

[4. React.js] Multiple Dependency Array in fetchData()

로그앤 2023. 6. 18. 18:58

In React, when you need to fetch data from multiple dependencies (such as multiple APIs or endpoints), 

you can make use of Promise.all() to handle multiple asynchronous requests. 

Promise.all() allows you to wait for multiple promises to resolve and then gather the results. 

Here's an example of how you can fetch data from multiple dependencies in React using Promise.all():

 

import React, { useEffect, useState } from 'react';

const fetchData = async () => {
  const [data1, data2, data3] = await Promise.all([
    fetch('https://api.example.com/endpoint1').then(response => response.json()),
    fetch('https://api.example.com/endpoint2').then(response => response.json()),
    fetch('https://api.example.com/endpoint3').then(response => response.json()),
  ]);

  // Process the fetched data as needed
};

const MyComponent = () => {
  useEffect(() => {
    fetchData();
  }, []);

  return (
    <div>
      {/* Render your component content */}
    </div>
  );
};

export default MyComponent;

In the example above, the fetchData function uses Promise.all() to fetch data from multiple dependencies simultaneously.Each fetch request is defined within an array passed to Promise.all(). Each fetch request returns a promise that resolves to the response object, which is then converted to JSON using the .json() method.

 

Once all the promises are resolved, the fetched data is destructured and stored in separate variables (data1, data2, data3 in this example).

 

The fetchData function can be called within the useEffect hook to fetch the data when the component mounts. You can modify the URLs and the number of fetch requests based on your specific dependencies. Please note that fetch is a built-in browser API for making HTTP requests. If you need to handle more complex scenarios or use libraries like Axios, you can adapt the code accordingly.