import React, { createContext, useContext, useState } from 'react'; import type { ToastMessage } from './Toast'; import Toast from './Toast'; type Context = Readonly<{ showToast: (message: ToastMessage) => void; }>; export const ToastContext = createContext({ // eslint-disable-next-line @typescript-eslint/no-empty-function showToast: (_: ToastMessage) => {}, }); const getID = (() => { let id = 0; return () => { return id++; }; })(); type ToastData = ToastMessage & { id: number; }; type Props = Readonly<{ children: React.ReactNode; }>; export function useToast() { return useContext(ToastContext); } export default function ToastsProvider({ children }: Props) { const [toasts, setToasts] = useState>([]); function showToast({ title, subtitle, variant }: ToastMessage) { setToasts([{ id: getID(), subtitle, title, variant }, ...toasts]); } function closeToast(id: number) { setToasts((oldToasts) => { const newToasts = oldToasts.filter((toast) => toast.id !== id); return newToasts; }); } return ( {children}
{/* Notification panel, dynamically insert this into the live region when it needs to be displayed */} {toasts.map(({ id, title, subtitle, variant }) => ( { closeToast(id); }} /> ))}
); }