Skip to content

Instantly share code, notes, and snippets.

@robsonkades
Created August 9, 2022 19:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robsonkades/7a5e72b66eefea8e74c0e268b305df2b to your computer and use it in GitHub Desktop.
Save robsonkades/7a5e72b66eefea8e74c0e268b305df2b to your computer and use it in GitHub Desktop.
notistack
import React from 'react';
import { SnackbarProvider } from 'notistack';
import { notifications } from '@/config';
import Notifier from './Notifier';
const Notification: React.FC = () => {
return (
<SnackbarProvider maxSnack={notifications.maxSnack}>
<Notifier />
</SnackbarProvider>
);
};
export default Notification;
import React, { useCallback, useEffect, useRef } from 'react';
import { SnackbarKey, useSnackbar } from 'notistack';
import useNotifications from '@/store/notification';
const Notifier: React.FC = () => {
const [notifications, actions] = useNotifications();
const { enqueueSnackbar, closeSnackbar } = useSnackbar();
const displayed = useRef<SnackbarKey[]>([]);
const storeDisplayed = useCallback((key: SnackbarKey) => {
displayed.current = [...displayed.current, key];
}, []);
const removeDisplayed = useCallback((key: SnackbarKey) => {
displayed.current = [...displayed.current.filter((_key) => key !== _key)];
}, []);
useEffect(() => {
notifications.forEach(({ message, options, dismissed }) => {
if (dismissed) {
// dismiss snackbar using notistack
closeSnackbar(options.key);
return;
}
// do nothing if snackbar is already displayed
if (options.key && displayed.current.includes(options.key)) return;
// display snackbar using notistack
enqueueSnackbar(message, {
...options,
onExited(event, key) {
// removen this snackbar from the store
actions.remove(key);
removeDisplayed(key);
},
});
// keep track of snackbars that we've displayed
options.key && storeDisplayed(options.key);
});
}, [actions, closeSnackbar, enqueueSnackbar, notifications, removeDisplayed, storeDisplayed]);
return null;
};
export default Notifier;
const [, notificationsActions] = useNotifications();
notificationsActions.push({
options: {
content: (
<Alert severity="error">
<AlertTitle>Erro</AlertTitle>
{message}
</Alert>
),
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment