-
Notifications
You must be signed in to change notification settings - Fork 6.5k
Expand file tree
/
Copy pathindex.tsx
More file actions
54 lines (42 loc) · 1.46 KB
/
index.tsx
File metadata and controls
54 lines (42 loc) · 1.46 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
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';
import styles from './index.module.css';
type NotificationContextType = {
message: string | ReactNode;
duration: number;
} | null;
const NotificationContext = createContext<NotificationContextType>(null);
export const NotificationDispatch = createContext<
Dispatch<SetStateAction<NotificationContextType>>
>(() => {});
export const useNotification = () => useContext(NotificationDispatch);
export const NotificationProvider: FC<PropsWithChildren> = ({ 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}
{notification && (
<Notification duration={notification.duration}>
{notification.message}
</Notification>
)}
<Toast.Viewport className={styles.viewport} />
</Toast.Provider>
</NotificationDispatch.Provider>
</NotificationContext.Provider>
);
};