Search code examples
reactjsmobx-react-form

Making a one time API call by removing the map function


I am new to ReactJs and I am having difficulties understanding below change. When a form is submitted, the below code makes call to API based on number of item present.

I have decided not to use map function but with a single call by removing map.

submitForm() {
  // Remove map from below and make it as a single call instead multiple calls to API
  const bucketsInfo = formState.formData.step1.variants.map((item, i) => {
    const formBody = {
      buckets: [],
      control: formState.formData.step2.controlOptions
    };
    formState.formData.step2.variants.forEach((items, j) => {
      formBody.buckets.push({
        crossDomainSiteId: formState.formData.step2.variants[j].siteID.value,
      });
    });
    return axios.post("/guinness_api/experiments/experiment", formBody);
  });
}

Can somebody suggest me what's the best thing to do here.


Solution

  • Well, your code is still a bit convoluted, and you have a loop inside a loop which seems a bit unnecessary here.

    If I understood correctly what you need here, the refactored example would be:

    submitForm() {
        const { step2 } = formState.formData;
        const step2Variants = step2.variants;
    
        // Map already returns each variant, no need to foreach it with index
        const buckets = step2Variants.map(variant => ({
          crossDomainSiteId: variant.siteID.value
        }));
    
        /** Creates formbody object from buckets populated with map, 
         *    and takes control options from step 2 
         */
        const formBody = {
          buckets,
          control: step2.controlOptions
        };
    
        return axios.post('/guinness_api/experiments/experiment', formBody);
    }