I have stumbled upon something interesting. When I create a new object setting a new key for a method, it doesnt handle it correctly when trying to access (use) it. Please see the example below:
const cases = [
{ instance: instance.mydecorator, triggerEffects: useMyDecorator },
];
then I want to loop through as follows:
cases.forEach(({ instance, triggerEffects }) => {
instance = [
Story => {
triggerEffects();
return <Story />;
},
];
});
the example above doesn not work: instance != instance.mydecorator, so the array is not set correctly.
What works is:
const cases = [
{ instance: instance, triggerEffects: useMyDecorator },
];
cases.forEach(({ instance, triggerEffects }) => {
instance.mydecorator = [
Story => {
triggerEffects();
return <Story />;
},
];
});
Any help in understanding this behaviour would be appreciated! Thanks
Problem with your code is destructure you are using in foreach callback input parameters - this part => cases.forEach(({ instance, triggerEffects })...
. When you do like this you destructured array element, and when looking your array declaration instance points to some other instance object, so in destructure { instance, triggerEffects }
instance will point to right side instance from your array declaration - you basically accessed(marked with THIS ONE) to const cases = [ { instance: instance(THIS ONE), triggerEffects: useMyDecorator }, ];
and not the one on the left side as you were expecting.
What you need to do is to avoid destructure in this case, since you do not want to modify that right side instance, but actual element of the array. Do like this:
cases.forEach(element => {
element.instance = [
Story => {
element.triggerEffects();
return <Story />;
},
];
});