Skip to content

Instantly share code, notes, and snippets.

@justin-lyon
Last active November 25, 2022 05:17
Show Gist options
  • Save justin-lyon/477fa7db2735243f24bbe665c117c23c to your computer and use it in GitHub Desktop.
Save justin-lyon/477fa7db2735243f24bbe665c117c23c to your computer and use it in GitHub Desktop.
Sample SF LWC toaster utility
// SAMPLE USAGE
import * as toaster from 'c/toaster';
export default class MyComponent extends LightningElement {}
connectedCallback() {
toaster.init(this);
}
save() {
toaster.success('Success!', 'Good job!');
}
}
// TOASTER UTIL
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
let component = null;
const init = (cmp) => {
component = cmp;
};
const toast = (title, message, variant, mode) => {
if (!component) {
throw new Error('Component is null. Call init with `this`.');
}
const event = new ShowToastEvent({
title,
message,
variant,
mode
});
component.dispatchEvent(event);
};
const error = (title, message) => {
toast(title, message, 'error', 'sticky');
};
const warning = (title, message) => {
toast(title, message, 'warning', 'pester');
};
const success = (title, message) => {
toast(title, message, 'success', 'dismissible');
};
const info = (title, message) => {
toast(title, message, 'info', 'dismissible');
};
export { init, error, warning, success, info };
@justin-lyon
Copy link
Author

The usage required a tiny bit of boilerplate in the connectedCallback, but I think it's better than having to deal with the ShowToastEvent import and verbose method signature(s) in order to get to the final dispatchEvent call.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment