43 lines
1.3 KiB
TypeScript
43 lines
1.3 KiB
TypeScript
import { useState, useCallback, useRef, createContext, useContext } from "react";
|
|
import type { ReactNode } from "react";
|
|
import React from "react";
|
|
|
|
export type ToastType = "success" | "error" | "info";
|
|
|
|
export interface Toast {
|
|
id: number;
|
|
message: string;
|
|
type: ToastType;
|
|
}
|
|
|
|
interface ToastContextValue {
|
|
toasts: Toast[];
|
|
addToast: (message: string, type?: ToastType) => void;
|
|
removeToast: (id: number) => void;
|
|
}
|
|
|
|
const ToastContext = createContext<ToastContextValue | null>(null);
|
|
|
|
export function ToastProvider({ children }: { children: ReactNode }) {
|
|
const [toasts, setToasts] = useState<Toast[]>([]);
|
|
const nextId = useRef(0);
|
|
|
|
const removeToast = useCallback((id: number) => {
|
|
setToasts((prev) => prev.filter((t) => t.id !== id));
|
|
}, []);
|
|
|
|
const addToast = useCallback((message: string, type: ToastType = "info") => {
|
|
const id = nextId.current++;
|
|
setToasts((prev) => [...prev, { id, message, type }]);
|
|
setTimeout(() => removeToast(id), 4000);
|
|
}, [removeToast]);
|
|
|
|
return React.createElement(ToastContext.Provider, { value: { toasts, addToast, removeToast } }, children);
|
|
}
|
|
|
|
export function useToast(): ToastContextValue {
|
|
const ctx = useContext(ToastContext);
|
|
if (!ctx) throw new Error("useToast must be used within ToastProvider");
|
|
return ctx;
|
|
}
|