import React , { createContext , useContext , useCallback , useState } from 'react' ; import { uuid } from 'uuidv4' ; import ToastContainer from '../components/ToastContainer' ; export interface ToastMessage { id : string ; type ? : 'success' | 'error' | 'info' ; title : string ; description ? : string ; } interface ToastContextData { addToast ( message ) : void ; removeToast ( id ) : void ; } const ToastContext = createContext < ToastContextData > ( { } as ToastContextData ) ; export const ToastProvider = ( { children } ) => { const [ messages , setMessages ] = useState < ToastMessage [ ] > ( [ ] ) ; const addToast = useCallback ( ( { type , title , description } ) => { const id = uuid ( ) ; const toast = { id , type , title , description , } ; setMessages ( ( oldMessages ) => [ ... oldMessages , toast ] ) ; } , [ ] ) ; const removeToast = useCallback ( ( id ) => { setMessages ( ( state ) => state . filter ( ( message ) => message . id !== id ) ) ; } , [ ] ) ; return ( < ToastContext . Provider value = { { addToast , removeToast } } > { children } < ToastContainer messages = { messages } / > < /ToastContext.Provider>); } ; export function useToast ( ) { const context = useContext ( ToastContext ) ; if ( ! context ) { throw new Error ( 'useToast must be used within a ToastProvider' ) ; } return context ; }