chore: add client/src/hooks/use-toast.ts
This commit is contained in:
parent
d05c981dae
commit
18cf3e8353
1 changed files with 40 additions and 0 deletions
40
client/src/hooks/use-toast.ts
Normal file
40
client/src/hooks/use-toast.ts
Normal file
|
|
@ -0,0 +1,40 @@
|
|||
import { useState, useCallback } from "react";
|
||||
|
||||
type ToastVariant = "default" | "destructive" | "success";
|
||||
|
||||
interface Toast {
|
||||
id: string;
|
||||
title?: string;
|
||||
description?: string;
|
||||
variant?: ToastVariant;
|
||||
}
|
||||
|
||||
let listeners: Array<(toasts: Toast[]) => void> = [];
|
||||
let toastList: Toast[] = [];
|
||||
|
||||
function notify() {
|
||||
listeners.forEach((l) => l([...toastList]));
|
||||
}
|
||||
|
||||
export function toast(options: Omit<Toast, "id">) {
|
||||
const id = Math.random().toString(36).slice(2);
|
||||
toastList = [...toastList, { id, ...options }];
|
||||
notify();
|
||||
setTimeout(() => {
|
||||
toastList = toastList.filter((t) => t.id !== id);
|
||||
notify();
|
||||
}, 4000);
|
||||
}
|
||||
|
||||
export function useToast() {
|
||||
const [toasts, setToasts] = useState<Toast[]>([]);
|
||||
|
||||
const subscribe = useCallback(() => {
|
||||
listeners.push(setToasts);
|
||||
return () => {
|
||||
listeners = listeners.filter((l) => l !== setToasts);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return { toasts, toast, subscribe };
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue