1

I have an LWC that takes an object returned from the server-side, makes it mutable by cloning, and then adds a get property via Object.defineProperty:

    const t = {...template};
    Object.defineProperty(
        t,
        'typeAndName',
        { get() { return t.type + ': ' + t.MasterLabel; } }
    );

    // Correct output here
    console.log('typeAndName', t.typeAndName);

But when rendered in a lightning-datatable (actually a lightning-tree-grid that is based on that) column:

        {
            type: 'text',
            fieldName: 'typeAndName',
            label: 'Type and Name',
        },

an empty string always results.

Is this a step too far for LWC given that properties are reactive? Or am I missing something else here?

PS

Just looked at the code again and this cleaner spread syntax version does work so for me so the original question is just of academic interest now:

    const t = {
        ...template,
        get typeAndName() { return t.type + ': ' + t.MasterLabel; }
    };

1 Answer 1

1
{ get() { return t.type + ': ' + t.MasterLabel; } }

Should have been:

{ get: function() { return t.type + ': ' + t.MasterLabel; } }

You can also use a template literal here:

{ get: function() { return `${this.type}: ${this.MasterLabel}`; } }

The descriptor object is in normal object syntax, just as you'd say { message: 'Hello World' }.

Here's a working example.

3
  • So the (presumably) older syntax is needed not the (presumably) newer get() syntax? Good to know for other cases; think the spread is the way to go in this example. And +1 for the template literal us.
    – Keith C
    Commented Dec 22, 2021 at 13:26
  • @KeithC Both { fn() {...} } and { fn: {...} } are supported even in older editions. The difference between the two is technical (the former is a named function, the latter is a property pointing to an anonymous function). For whatever reason, JS tends to distinguish between these two in some cases, and this is one of those cases. Unless the docs show otherwise, presume that only the latter method is supported.
    – sfdcfox
    Commented Dec 22, 2021 at 13:46
  • Thanks, useful advice (as always).
    – Keith C
    Commented Dec 22, 2021 at 14:41

You must log in to answer this question.

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