Skip to content

Instantly share code, notes, and snippets.

@el3um4s
Created October 15, 2022 14:00
Show Gist options
  • Save el3um4s/27248af596212619ba145e828d306ba7 to your computer and use it in GitHub Desktop.
Save el3um4s/27248af596212619ba145e828d306ba7 to your computer and use it in GitHub Desktop.
MEDIUM - How To Show Notifications in Web Application - 06
import { writable } from "svelte/store";
import type { Writable } from "svelte/store";
const TIMEOUT = 3000;
type MessageType = "default" | "danger" | "warning" | "info" | "success";
export interface Msg {
type: MessageType;
message: string;
timeout?: number;
}
interface Message {
id: string;
msg: Msg;
}
const idGenerator = (): string =>
"_" + Math.random().toString(36).substring(2, 9);
const notificationStore: Writable<Message[]> = writable([]);
const notifications = {
subscribe: notificationStore.subscribe,
send: (msg: Msg, id: string = idGenerator()) => {
notificationStore.update((n) => {
return [...n, { id, msg }];
});
setTimeout(
() => {
notificationStore.update((n) => {
return n.filter((m) => m.id !== id);
});
},
msg?.timeout ? msg.timeout : TIMEOUT
);
},
remove: (id: string) => {
notificationStore.update((n) => {
return n.filter((m) => m.id !== id);
});
},
};
export default notifications;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment