Last active
November 25, 2022 05:17
-
-
Save justin-lyon/477fa7db2735243f24bbe665c117c23c to your computer and use it in GitHub Desktop.
Sample SF LWC toaster utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SAMPLE USAGE | |
import * as toaster from 'c/toaster'; | |
export default class MyComponent extends LightningElement {} | |
connectedCallback() { | |
toaster.init(this); | |
} | |
save() { | |
toaster.success('Success!', 'Good job!'); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.