-
Notifications
You must be signed in to change notification settings - Fork 4
/
ToastNotifier.tsx
50 lines (42 loc) · 1.76 KB
/
ToastNotifier.tsx
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
import React, { useCallback, useState } from 'react';
import { useGlobalStore } from '../../shared/global-store-provider/GlobalStoreProvider';
import { autorun } from 'mobx';
import { OptionsObject, SnackbarAction, useSnackbar } from 'notistack';
import { IToastNotification } from './ToastNotifier.types';
import { Button } from 'semantic-ui-react';
interface IProps {}
export const ToastNotifier: React.FC<IProps> = (props) => {
const { toastStore } = useGlobalStore();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const [displayed, setDisplayed] = useState<(string | number)[]>([]);
const action: SnackbarAction = useCallback(
(key) => <Button circular={true} size="mini" icon="close" onClick={() => closeSnackbar(key)} />,
[closeSnackbar]
);
autorun(() => {
toastStore.notifications.forEach((notification: IToastNotification) => {
const shapedOptions: OptionsObject = {
action,
anchorOrigin: { vertical: 'bottom', horizontal: 'center' },
autoHideDuration: 3000,
disableWindowBlurListener: true,
variant: notification.options.variant,
};
const key = notification.options.key as string;
// https://github.com/iamhosseindhv/notistack/tree/master/examples/mobx-example
// Do nothing if snackbar is already displayed
if (displayed.includes(key)) {
return;
}
// Display snackbar using notistack
enqueueSnackbar(notification.message, shapedOptions);
// Keep track of snackbars that we've displayed
setDisplayed([...displayed, key]);
// Dispatch action to remove snackbar from mobx store
toastStore.removeToast(notification);
});
});
return null;
};
ToastNotifier.displayName = 'ToastNotifier';
ToastNotifier.defaultProps = {};