Skip to content

Instantly share code, notes, and snippets.

@developit
Created February 21, 2018 02:54
Show Gist options
  • Save developit/71a459bb7be7019ea92ba4a9eb2c4012 to your computer and use it in GitHub Desktop.
Save developit/71a459bb7be7019ea92ba4a9eb2c4012 to your computer and use it in GitHub Desktop.
import { Component } from 'preact';
import Snackbar from 'preact-material-components/Snackbar';
const TIMEOUT = 3;
export default class Toaster extends Component {
seen = [];
queue = [];
snackbarRef = c => {
this.snackbar = c;
};
queueClose() {
clearTimeout(this.closeTimer);
this.closeTimer = setTimeout(this.hide, (TIMEOUT + 2) * 1000);
}
hide = () => {
clearTimeout(this.closeTimer);
this.current = null;
this.setState({ visible: false });
};
show = callback => {
clearTimeout(this.closeTimer);
if (this.state.visible) return callback();
this.setState({ visible: true }, () => {
setTimeout(callback, 100);
});
};
notify(info) {
this.current = info;
if (this.seen.indexOf(info)===-1) this.seen.push(info);
this.show(() => {
if (this.snackbar) {
this.snackbar.MDComponent.show({
...info,
timeout: TIMEOUT*1000
});
}
if (!this.processQueue()) {
this.queueClose();
}
});
}
processQueue = () => {
let notif = this.queue.shift();
if (notif) {
this.notify(notif);
return true;
}
return false;
};
queueNotify(info) {
this.seen.push(info);
if (this.queue.push(info)===1) {
setTimeout(this.processQueue);
}
}
componentWillReceiveProps({ notifications=[] }) {
for (let i=0; i<notifications.length; i++) {
if (this.seen.indexOf(notifications[i])===-1) {
this.queueNotify(notifications[i]);
}
}
}
render(props, { visible }) {
return (
visible ? <Snackbar style={{ zIndex: 1001 }} ref={this.snackbarRef} /> : null
);
}
}
@jimfilippou
Copy link

jimfilippou commented May 24, 2020

Clearly you haven't included a manual on how to actually call this. To save newcomers from wasting more time here is how to use this code

this.notify({ message: "Message goes here" });

Passing just a string will warn you that there is no message

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