Share lwc modules as reusable utility components

bestpracticelightning-web-components

So I am looking to implement reusability pattern across Lwc's using utility components. What Im not understanding is limitations of importing modules/dependencies like ShowToastEvent.

If I create a simple test Lwc that imports ShowToastEvent and then dispatches an event the toast renders into UI as expected. However, if I then try to refactor the notification code into a standalone reusable function that is imported into an lwc it doesnt work as expected. The imported function is called successfully but the toast no longer renders – the ShowToastEvent module is no longer reference-able. I have tried both leaving "import { ShowToastEvent } from 'lightning/platformShowToastEvent';" in the original test component and importing it inside the utility component – neither works.

If anyone has created a reusable utility class that leverages modules like ShowToastEvent it'd be great to confirm with you how you've structured your components to make reuse possible.

Ive tried variations like below for the reusable component with no luck so far. The console shows function is recognised by importing 'parent' component, but the toast doesnt render.

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

function showNotification(title, message, variant, mode) {
    console.log('called...');
    const evt = new ShowToastEvent({
        title: title,
        message: message,
        variant: variant
    });
    this.dispatchEvent(evt);
}

export { showNotification, ShowToastEvent}

Best Answer

We have created reusable libraries and it is working as expected. For your use case where toast is not working, small change is required where you dispatching event.

import { ShowToastEvent } from 'lightning/platformShowToastEvent'
        
const showMessage = (page, t, m,type ) => {
const toastEvt = new ShowToastEvent({
            title: t,
            message:m,
            variant: type
        });
            page.dispatchEvent(toastEvt);
};
        
        //export it for other
export 
{
    showMessage
}

usage of this library:

import { showMessage} from 'c/commonLibrary';

showMessage(this,'Notification','Your Message','error');

In case of community,it might not work. You can use custom toast model which will use slds-notify slds-notify_toast css class.

Hope this will work for you.