How to call multiple different apis using useEffect hook in React

Viewed 963

I have a concern regarding calling the apis using axios in useEffect hook. For example, I have a react page where I am showing the all the list of consignments. A consignment can have a user from user list, a carrier from carrier list, an account from account list, a status from status list and a service from service list. All these lists are enumerated data. So, in this page where I have to get all the enumerated list before rendering the page, because in the react component, I have to display them as dropdown, so that users can apply filter on top of that. But getting the list of those enumerated data, I have to call the separate api. For example, getting users I have to call /users api and getting customers I have to call /customers api. My concern is do I need to call them using a single useEffect hook using the axios. Because I have to hit the server multiple times for getting those enumerated data. If the number of lists of enumerated data increases then my api request to the server will also increase. I don't know what is the best practice to deal with this kind of situation. Whether to create a single api so that the server is hit only once and all the enumerated data are returned or have the separate api and hit the server request to get separately to enumerated data. And hitting the server multiple times to get the enumerated data does it impact performance on the client-side I mean some memory leak? Just need some advice on that. Thanks in advance.

useEffect(() => {
  const loadData = async () => {
    try {
      dispatch(getLoad(true));
      const services = await Axios.get("/Services");

      const customers = await Axios.get("/Accounts/Customers");

      const resCarrier = await Axios.get("/Accounts/Carriers");

      const resStatuses = await Axios.get("/Status");

      setFilterData((prev) => ({
        ...prev,
        services: services.data,
        customers: customers.data,
        carriers: resCarrier.data,
        statuses: resStatuses.data,
      }));
      dispatch(getLoad(false));
    } catch (error) {
      dispatch(getLoad(false));
    }
  };
}, []);
1 Answers

You can use axios.all

axios.all([
   axios.get(`/Services`), 
   axios.get(`/Accounts/Customers`),
   axios.get(`/Accounts/Carriers`),
   axios.get(`/Status`)
 ])
 .then(axios.spread((services, customers, carriers, status) => {
   setFilterData((prev) => ({
    ...prev,
    services: services.data,
    customers: customers.data,
    carriers: carriers.data,
    statuses: status.data,
  }));
 }));
Related