UNPKG

pagamio-frontend-commons-lib

Version:

Pagamio library for Frontend reusable components like the form engine and table container

30 lines (29 loc) 1.55 kB
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { createContext, useCallback, useContext, useMemo, useState } from 'react'; import Toast from '../components/ui/Toast'; const ToastContext = createContext(undefined); export const useToast = () => { const context = useContext(ToastContext); if (!context) { throw new Error('useToast must be used within a ToastProvider'); } return context; }; export const ToastProvider = ({ children }) => { const [toasts, setToasts] = useState([]); const removeToast = useCallback((id) => { setToasts((prevToasts) => prevToasts.filter((toast) => toast.id !== id)); }, []); const addToast = useCallback((props) => { const { message, title = '', variant = 'info' } = props; const id = Date.now(); setToasts((prevToasts) => [...prevToasts, { id, title, message, variant }]); // Remove the toast automatically after 5 seconds setTimeout(() => { removeToast(id); }, 5000); }, [removeToast]); // Wrap the value in useMemo so it remains stable unless addToast changes const contextValue = useMemo(() => ({ addToast }), [addToast]); return (_jsxs(ToastContext.Provider, { value: contextValue, children: [children, _jsx("div", { className: "fixed right-0 top-4 z-50 m-4 space-y-2", style: { zIndex: 1000 }, children: toasts.map((toast) => (_jsx(Toast, { id: toast.id, title: toast.title, message: toast.message, variant: toast.variant, onClose: removeToast }, toast.id))) })] })); };