edtech / apps /admin /src /hooks /useToast.ts
CognxSafeTrack
feat: backlog P0→P3 — toast system, payments, tenant isolation, feedback handler, i18n parity
6dd9bad
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'),
};
}