1

I have done similar work in other projects, but for whatever reason, this is not working. The object created is {} instead of what I would expect, see code below...

javascript

import { LightningElement, track } from 'lwc';

const Referral = {
    ReferrorInformation : {
        ReferralOwner : "",
        CreatedDate : new Date().toISOString(),
        Email : "",
        Phone : "",
        Fax : "",
        School : ""
    }
}

export default class App extends LightningElement {
    referralToUpdate = Object.create(Referral);
    contactEmail = '[email protected]';
    userId = '1111222';
    contactFax = '555-1212';
    contactPhone = '555-1313';
    contact = { AccountId: 234 };
    output;

    renderedCallback() {
        this.output = JSON.stringify(this.referralToUpdate, null, 4);
    }

    handleClick = (event) => {
        this.referralToUpdate.updatedDate = new Date().toISOString();
        this.referralToUpdate.ReferrorInformation.Email = this.contactEmail;
        this.referralToUpdate.ReferrorInformation.ReferralOwner = this.userId;
        this.referralToUpdate.ReferrorInformation.Fax = this.contactFax;
        this.referralToUpdate.ReferrorInformation.Phone = this.contactPhone;
        this.referralToUpdate.ReferrorInformation.School = this.contact.AccountId;
        this.output = {...this.output};
    }
}

template

<template>
    {output}
    <p><button type="submit" onclick={handleClick} title="Refresh">Refresh</button></p>
</template>

What I would expect is the object properties are set, what I get is only the date that I set. I suspect it is a shallow clone issue, but not sure.

Any ideas?

2 Answers 2

1

Yes, it's a shallow clone issue. You can test this in your browser console (create a New Tab, and go to the browser's Developer Console):

const a = { b: { c: 'hello world' } };
const b = Object.create(a);
console.log(b); // {}

You need to use a deep-clone technique in order to recreate your object.

1
  • Yep that was it, tried a deep copy first, but didn't realize there was an error in my code and thought it was due to this issue so I backed out those changes. Thanks! Commented Dec 29, 2020 at 19:57
0

The accepted answer here is actually incorrect. It is not a shallow clone issue. The reason b is showing as an empty object is because of prototypal inheritance. if you were to console.log(b.__proto__), you'd see that those properties are on the prototype and both b.b as well as b.b.c are accessible.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .