-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathNotificationProvider.tsx
More file actions
57 lines (45 loc) · 1.52 KB
/
NotificationProvider.tsx
File metadata and controls
57 lines (45 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import * as Toast from '@radix-ui/react-toast';
import { createContext, useContext, useEffect, useState } from 'react';
import type {
Dispatch,
FC,
PropsWithChildren,
ReactNode,
SetStateAction,
} from 'react';
import Notification from '#ui/Common/Notification';
type NotificationContextType = {
message: string | ReactNode;
duration: number;
} | null;
type NotificationProps = { viewportClassName?: string };
const NotificationContext = createContext<NotificationContextType>(null);
export const NotificationDispatch = createContext<
Dispatch<SetStateAction<NotificationContextType>>
>(() => {});
export const useNotification = () => useContext(NotificationDispatch);
export const NotificationProvider: FC<PropsWithChildren<NotificationProps>> = ({
viewportClassName,
children,
}) => {
const [notification, dispatch] = useState<NotificationContextType>(null);
useEffect(() => {
const timeout = setTimeout(() => dispatch(null), notification?.duration);
return () => clearTimeout(timeout);
}, [notification]);
return (
<NotificationContext.Provider value={notification}>
<NotificationDispatch.Provider value={dispatch}>
<Toast.Provider>
{children}
<Toast.Viewport className={viewportClassName} />
{notification && (
<Notification duration={notification.duration}>
{notification.message}
</Notification>
)}
</Toast.Provider>
</NotificationDispatch.Provider>
</NotificationContext.Provider>
);
};