0

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 />
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Ali Ahmadi
  • 701
  • 6
  • 27

1 Answers1

0

You cannot call hook outside a react component

You can wrap useSnackbar as new hook

import { useSnackbar } from 'notistack'

const useToast = () => {
  const SnackBar = useSnackbar();

  const Toast = useCallback((message, snackProps) => SnackBar.enqueueSnackbar(message, {
    autoHideDuration: 2000,
    ...snackProps
  })), [SnackBar])

  const Success = useCallback((message) => Toast(message, {
    variant: 'success'
  }), [Toast])

  const Warning = useCallback((message) => Toast(message, {
    variant: 'warning'
  }), [Toast])

  const Info = useCallback((message) => Toast(message, {
    variant: 'info'
  }), [Toast])

  const Error = useCallback((message) => Toast(message, {
    variant: 'error'
  }), [Toast])

  return {
    Toast,
    Success,
    Warning,
    Info,
    Error,
  }
}

You can use it like this

const OtherComponent = () => {
  const { Success } = useToast()

  // You can call it here Success("message")
}
kennarddh
  • 2,186
  • 2
  • 6
  • 21