Home > Back-end >  Scoping of variable inside a javascript map
Scoping of variable inside a javascript map

Time:12-15

{charts.map( (ch, i) => {
   const tempApiDetails = {...apiDetails};
   tempApiDetails.apiOptions.params = generateParams(ch.dashBoardType, ch.reportType); 
   //above line is to generate params for API call

   <SimpleTable apiOptions={tempApiDetails} />
})}

in the above code the charts is having 3 items. but all three in the end is having the same params which is made for the last chart in the charts variable. Can somebody explain me what will be underlying principle for it?

CodePudding user response:

This has nothing to do with scope.

tempApiDetails is a shallow copy of apiDetails.

This means the value of tempApiDetails.apiOptions is the same each time it goes around the loop.

Since it is an object, and objects are stored by reference, every time you assign to apiOptions.params you are overwriting the params of the same object.

You need to make a clone of apiOptions.

const tempApiDetails = {
    ...apiDetails,
    apiOptions: {...apiDetails.apiOptions}
};

And you can do the whole thing in one go:

const tempApiDetails = {
    ...apiDetails,
    apiOptions: {
         ...apiDetails.apiOptions,
         params: generateParams(ch.dashBoardType, ch.reportType)
    }
};

For complex data structures you might want to look at the immer library which will take care of all the cloning for you.

const tempApiDetails = produce(apiDetails, draft => {
    draft.apiOptions.params = generateParams(ch.dashBoardType, ch.reportType);
});
  • Related