| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- "use client";
- import { type ReactNode, createContext, useContext, useState, useCallback } from "react";
- import { ToastContainer } from "@/components/theme/toast/ToastContainer";
- export type ToastType = "success" | "danger" | "warning" | "primary";
- export interface ToastDataType {
- id: string;
- message: string;
- type: ToastType;
- duration?: number;
- }
- export interface ToastContextType {
- toasts: ToastDataType[];
- addToast: (_: Omit<ToastDataType, "id">) => void;
- removeToast: (_: string) => void;
- }
- const ToastContext = createContext<ToastContextType | undefined>(undefined);
- export const ToastProvider = ({ children }: { children: ReactNode }) => {
- const [toasts, setToasts] = useState<ToastDataType[]>([]);
- const removeToast = useCallback((id: string) => {
- setToasts((prev) => prev.filter((toast) => toast.id !== id));
- },[]);
- const addToast = useCallback((toast: Omit<ToastDataType, "id">) => {
- const id = crypto.randomUUID();
- const newToast = { id, ...toast };
- setToasts((prev) => [...prev, newToast]);
- setTimeout(() => {
- removeToast(id);
- }, toast.duration || 5000);
- },[removeToast]);
-
- return (
- <ToastContext.Provider value={{ toasts, addToast, removeToast }}>
- <ToastContainer />
- {children}
- </ToastContext.Provider>
- );
- };
- export const useToast = () => {
- const context = useContext(ToastContext);
- if (!context) {
- throw new Error("useToast must be used within a ToastProvider");
- }
- return context;
- };
|