4

If I extends a base lightning-datatable like this Lifecycle hooks in the extended LWC will not work when the Base Component is calling connectedCallback.

connectedCallback will be called but clicking a row acation will not invoke handleRowAction.

my-datatable.html

<template></template>

my-datatable.js (with problematic connectedCallback)

import LightningDatatable from 'lightning/datatable';

export default class MyTable extends LightningDatatable {
    connectedCallback() {
        console.log("connectedCallback");
    }
}

the handleRowActions (or other lifecycle hooks) will not be called

mypage.html

<template>
    <c-mytable key-field="id"
                data={data}
                columns={columns}
                onrowaction={handleRowAction}>
    </c-mytable>
</template>

mypage.js

import { LightningElement, track } from 'lwc';

export default class MyPage extends LightningElement {

    ...

    handleRowAction(event) {
        console.log("handleRowAction");
    }
}
2
  • 3
    Have you tried invoking the base class's connectedCallback, from within your own, like super.connectedCallback()? – Phil W Nov 10 '20 at 14:30
  • Awesom this works! Would you mind making this an answer with some documentation reference and explanation? – Robert Sösemann Nov 10 '20 at 14:38
7

The LWC lifecycle hooks are simply methods from the LightningElement which can be implemented at any level within the LWC inheritance hierarchy. It happens that the lightning-datatable itself makes use of the connectedCallback to perform necessary setup, including wiring up the row action handling.

If you override such a method in an LWC that is itself already implementing it you have to provide all the processing done in the superclass in your own implementation as well as your own processing. The easiest way to achieve this is to simply "augment" the method by calling the super class's version of the method then doing your own thing (it is usually best to do the super class call first for consistency and to avoid doing any processing of your own if the super class would barf).

In this case you simply need:

    connectedCallback() {
        // Allow the super class to do what it wants to do first
        super.connectedCallback();

        // Now do the special processing needed here
        console.log("connectedCallback");
    }

In terms of documentation, sadly the lifecycle hook docs fail to mention this aspect, and the lightning-datatable documentation also fails to mention the fact that it implements the connectedCallback.

The rule of thumb is that if you ever inherit from anything other than LightningElement, treat it as a black box and always call the super versions of the lifecycle hook methods "just in case".

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.