The following code used to work in earlier versions of ReactJS but now it seems useSnackbarRef
loses its value and is undefined inside handler
function, what has changed in React and how can I fix this utility?
The goal of the utility is to enable me to call enqueueSnackbar
from outside of react components.
import { useSnackbar } from 'notistack';
let useSnackbarRef;
export const SnackbarUtilsConfigurator = () => {
useSnackbarRef = useSnackbar();
return null;
};
const handler = {
success(msg) {
this.toast(msg, { variant: 'success' });
},
warning(msg) {
this.toast(msg, { variant: 'warning' });
},
info(msg) {
this.toast(msg, { variant: 'info' });
},
error(msg) {
this.toast(msg, { variant: 'error' });
},
toast(msg, { variant = 'default', ...restProps }) {
useSnackbarRef.enqueueSnackbar(msg, { variant, autoHideDuration: 2000, ...restProps });
},
};
export default handler;
Please note I also render SnackbarUtilsConfigurator
inside my app.js
like this:
<SnackbarUtilsConfigurator />