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
Asked
Active
Viewed 1,236 times
1 Answers
0
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

Yassine CHABLI
- 3,459
- 2
- 23
- 43