Notistack enqueueSnackbar usage outside component

1.6k Views Asked by At

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

1

There are 1 best solutions below

0
On
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