Thursday 6 April 2023

React- nested API call asyn - await

useEffect(() => {

  const getData = async () => {

      try {

          const { data } = await fetchContext.authAxios.get('/myapi/' + auth.authState.id);

          const customerIdList = data.map(value => value.customerID);

          // this fetches list of all customer details in one go

          const customersDetails = (await fetchContext.authAxios.post('/mySecondApi/', {customerIdList})).data;

          // please make necessary changes to the api call

          const updatedData = data.map(value => {

                 // filtering the particular customer's detail and updating the data from first api call

                 const customerDetails = customersDetails.filter(c => c.customerID === value.customerID)[0];

                  

                  return {

                      ...value, // de-structuring

                      customerID: customerDetails

                      // as you asked customer data should replace the customerID field

                  }

              }

          );

          setData(updatedData); // this data would contain the other details of customer in it's customerID field, along with all other fields returned by your first api call

      } catch (err) {

          console.log(err);

      }

  };

  getData();

}, [fetchContext]); 

No comments:

Post a Comment

React + Typescript_ Module federation _ Micro Front end -Standalone and integrated

Module Federation The Module Federation is actually part of Webpack config. This config enables us to expose or receive different parts of t...