import React, { createContext, FunctionComponent, useEffect, useState, memo, } from 'react' type NotificationBarProps = Readonly<{ duration?: number | null }> type NotificationProps = Readonly<{ duration: number | null notification: string setNotification: any }> type NotificationBarProviderProps = Readonly<{ children: any }> type State = string | null type Context = { notification: string | null setNotification: (notification: any) => void } const { Provider, Consumer } = createContext({ notification: null, setNotification: (notification) => notification, }) const NotificationBase: FunctionComponent = ({ duration = null, notification, setNotification, }) => { const dismissNotification = () => setNotification(null) useEffect(() => { if (!duration) return const timer = setTimeout(dismissNotification, duration) return () => clearTimeout(timer) }) return notification ? (
{notification}
) : null } export const Notification = memo(NotificationBase) export const NotificationBar: FunctionComponent = ({ duration = 2000, }) => { return ( {({ notification, setNotification }) => notification && setNotification ? ( ) : null } ) } const NotificationBarProviderBase: FunctionComponent< NotificationBarProviderProps > = ({ children }) => { const [notification, setNotification] = useState(null) return ( {children} ) } export const NotificationBarProvider = memo(NotificationBarProviderBase) export const NotificationBarConsumer = Consumer