Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to reassign object method/Property to new Object?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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 />;
    },
  ];
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading