Notistack is great tool for handling notifications. Sometimes we create a separate js file for calling api. But normally it is not available outside of react components.
Today we are gonna solve this issue.For this we have to follow couple of steps.
I'm showing this for NextJS
JavaScript
import { useSnackbar } from 'notistack';
let useSnackbarRef;
export const SnackbarUtilsConfigurator = () => {
useSnackbarRef = useSnackbar();
return null;
};
export default {
success(msg) {
this.toast(msg, 'success');
},
warning(msg) {
this.toast(msg, 'warning');
},
info(msg) {
this.toast(msg, 'info');
},
error(msg) {
this.toast(msg, 'error');
},
toast(msg, variant = 'default') {
useSnackbarRef.enqueueSnackbar(msg, { variant, autoHideDuration: 1500 });
},
};
TypeScript
import { useSnackbar, VariantType, WithSnackbarProps } from 'notistack'
let useSnackbarRef: WithSnackbarProps
export const SnackbarUtilsConfigurator: React.FC = () => {
useSnackbarRef = useSnackbar()
return null
}
export default {
success(msg: string) {
this.toast(msg, 'success')
},
warning(msg: string) {
this.toast(msg, 'warning')
},
info(msg: string) {
this.toast(msg, 'info')
},
error(msg: string) {
this.toast(msg, 'error')
},
toast(msg: string, variant: VariantType = 'default') {
useSnackbarRef.enqueueSnackbar(msg, { variant })
}
}
Import SnackbarProvider from notistack
Import the SnackbarUtilsConfigurator function in _app.js.
Thank you for reading
Top comments (1)
Hello @sakiblite, In this code above "WithSnackbarProps" is no more available in notistack, can you help me with this ?