'Notistack enqueueSnackbar usage outside component
Is there any way to use enqueueSnackbar() outside the react component? For example, I want to show an alert on the service API request error. Api service request is called from redux action
Solution 1:[1]
import { useSnackbar, VariantType, WithSnackbarProps } from 'notistack'
import React from 'react'
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 })
}
}
To initialize:
<SnackbarProvider maxSnack={3} anchorOrigin={{ horizontal: 'center', vertical: 'bottom' }}>
<SnackbarUtilsConfigurator />
...
</SnackbarProvider>
And then, anywhere in code:
import SnackbarUtils from 'src/utils/SnackbarUtils'
SnackbarUtils.success('Success ?')
Also, with this implementation, you can expose anything the Hook or HOC was providing easily
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Yassine CHABLI |