src/lib/store/toastStore.ts (view raw)
1import { writable } from "svelte/store";
2
3type ToastType = "info" | "error" | "success" | "warning";
4
5export interface Toast {
6 id: number;
7 message: string;
8 type: ToastType;
9}
10
11export const toastStore = writable(<Toast[]>[]);
12
13// Display toast
14export const addToast = (message: string, type: ToastType = "info") => {
15 const id = Math.random();
16 const newToast = { id, message, type };
17 toastStore.update((toasts: Toast[]) => [...toasts, newToast]);
18};
19
20// Store toast in session storage and display it at next page load
21export const addSessionToast = (message: string, type: ToastType = "info") => {
22 const toast = JSON.stringify({ message, type });
23 sessionStorage.setItem("toast", toast);
24};
25
26export const removeToast = (id: number) =>
27 toastStore.update((toasts: Toast[]) =>
28 toasts.filter(toast => toast.id !== id)
29 );