"use client"; import React, { createContext, useCallback, useContext, useMemo, useState } from "react"; export type Toast = { id: string; message: string; type?: "info" | "success" | "error" }; type ToastContextValue = { show: (message: string, type?: Toast["type"]) => void; }; const ToastContext = createContext(undefined); export function ToastProvider({ children }: { children: React.ReactNode }) { const [toasts, setToasts] = useState([]); const show = useCallback((message: string, type: Toast["type"] = "info") => { const id = Math.random().toString(36).slice(2); setToasts((t) => [...t, { id, message, type }]); setTimeout(() => setToasts((t) => t.filter((x) => x.id !== id)), 3500); }, []); const value = useMemo(() => ({ show }), [show]); return ( {children}
{toasts.map((t) => (
{t.message}
))}
); } export function useToast() { const ctx = useContext(ToastContext); if (!ctx) throw new Error("useToast must be used within ToastProvider"); return ctx; }