{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?
In JavaScript there are two types of scope: JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.
Global scope. JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.
Variables declared with the var keyword can NOT have block scope. Variables declared inside a { } block can be accessed from outside the block. Variables declared within a JavaScript function, become LOCAL to the function. They can only be accessed from within the function.
A variable can also have a local scope, i.e it can only be accessed within a function. In the above program, variable a is a global variable and variable b is a local variable. The variable b can be accessed only inside the function greet. Hence, when we try to access variable b outside of the function, an error occurs.
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With