()
| 6 | let displayed = [] |
| 7 | |
| 8 | const useNotifier = () => { |
| 9 | const dispatch = useDispatch() |
| 10 | const notifier = useSelector((state) => state.notifier) |
| 11 | const { notifications } = notifier |
| 12 | |
| 13 | const { enqueueSnackbar, closeSnackbar } = useSnackbar() |
| 14 | |
| 15 | const storeDisplayed = (id) => { |
| 16 | displayed = [...displayed, id] |
| 17 | } |
| 18 | |
| 19 | const removeDisplayed = (id) => { |
| 20 | displayed = [...displayed.filter((key) => id !== key)] |
| 21 | } |
| 22 | |
| 23 | React.useEffect(() => { |
| 24 | notifications.forEach(({ key, message, options = {}, dismissed = false }) => { |
| 25 | if (dismissed) { |
| 26 | // dismiss snackbar using notistack |
| 27 | closeSnackbar(key) |
| 28 | return |
| 29 | } |
| 30 | |
| 31 | // do nothing if snackbar is already displayed |
| 32 | if (displayed.includes(key)) return |
| 33 | |
| 34 | // display snackbar using notistack |
| 35 | enqueueSnackbar(message, { |
| 36 | key, |
| 37 | ...options, |
| 38 | onClose: (event, reason, myKey) => { |
| 39 | if (options.onClose) { |
| 40 | options.onClose(event, reason, myKey) |
| 41 | } |
| 42 | }, |
| 43 | onExited: (event, myKey) => { |
| 44 | // remove this snackbar from redux store |
| 45 | dispatch(removeSnackbar(myKey)) |
| 46 | removeDisplayed(myKey) |
| 47 | } |
| 48 | }) |
| 49 | |
| 50 | // keep track of snackbars that we've displayed |
| 51 | storeDisplayed(key) |
| 52 | }) |
| 53 | }, [notifications, closeSnackbar, enqueueSnackbar, dispatch]) |
| 54 | } |
| 55 | |
| 56 | export default useNotifier |
no test coverage detected