File size: 1,436 Bytes
6dd9bad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | import { createContext, useContext, useState, useCallback } from 'react';
export type ToastType = 'success' | 'error' | 'info' | 'warning';
export interface Toast {
id: string;
type: ToastType;
message: string;
}
interface ToastContextValue {
toasts: Toast[];
addToast: (message: string, type: ToastType) => void;
removeToast: (id: string) => void;
}
export const ToastContext = createContext<ToastContextValue>({
toasts: [],
addToast: () => {},
removeToast: () => {},
});
export function useToastState() {
const [toasts, setToasts] = useState<Toast[]>([]);
const addToast = useCallback((message: string, type: ToastType) => {
const id = crypto.randomUUID();
setToasts(prev => [...prev, { id, type, message }]);
setTimeout(() => {
setToasts(prev => prev.filter(t => t.id !== id));
}, 4000);
}, []);
const removeToast = useCallback((id: string) => {
setToasts(prev => prev.filter(t => t.id !== id));
}, []);
return { toasts, addToast, removeToast };
}
export function useToast() {
const { addToast } = useContext(ToastContext);
return {
success: (message: string) => addToast(message, 'success'),
error: (message: string) => addToast(message, 'error'),
info: (message: string) => addToast(message, 'info'),
warning: (message: string) => addToast(message, 'warning'),
};
}
|