import React , { createContext , useState } from 'react' ; export type AlertType = 'error' | 'info' | 'success' | 'warning' ; export interface AlertWithoutId { content : React . ReactNode ; type : AlertType ; } export interface Alert extends AlertWithoutId { id : number ; timerCb : number ; } export const AlertsContext = createContext ( { enqueue : ( newAlertWithoutId ) => { console . error ( 'No context provider found above in the tree.' ) ; } , remove : ( Alertid ) => { console . error ( 'No context provider found above in the tree.' ) ; } , alerts : [ ] as Alert [ ] , } ) ; interface Props { children : React . ReactNode ; } export function AlertsContextProvider ( props ) { const [ { alerts , nextAlertId } , setAlerts ] = useState ( { alerts : [ ] as Alert [ ] , nextAlertId : 0 , } ) ; const remove = ( alertId ) : void => { setAlerts ( { alerts : [ ... alerts . filter ( ( { id } ) => id !== alertId ) ] , nextAlertId , } ) ; } ; const enqueue = ( newAlertWithoutId ) : void => { setAlerts ( { alerts : [ ... alerts , { ... newAlertWithoutId , id : nextAlertId , timerCb : setTimeout ( ( ) => { remove ( nextAlertId ) ; } , 3000 ) , } , ] , nextAlertId : nextAlertId + 1 , } ) ; } ; return ( < AlertsContext . Provider value = { { enqueue , remove , alerts } } > { props . children } < /AlertsContext.Provider>); }