reactjsdebuggingundefinedtypeerrornotistack

What is causing this enqueue snackbar error for notistack?


I'm trying to use the useSnack hook from notistack library but I keep getting this error

TypeError: Cannot destructure property 'enqueueSnackbar' of 'Object(...)(...)' as it is undefined.

Here is the code:

import React, { useContext, useEffect } from "react";
import AlertContext from "../context/alert/alertContext";
import { SnackbarProvider, useSnackbar } from "notistack";

const Alerts = (props) => {
  const alertContext = useContext(AlertContext);
  // This line below is where the error seems to be
  const { enqueueSnackbar } = useSnackbar();
  useEffect(() => {
    alertContext.msg !== "" &&
      enqueueSnackbar(alertContext.msg, {
        variant: alertContext.type,
      });
  }, [alertContext]);
  return <SnackbarProvider maxSnack={4}>{props.children}</SnackbarProvider>;
};

export default Alerts;

Solution

  • useSnackbar hook accessible anywhere down the tree from SnackbarProvider.

    So you cannot use it in the same component as SnackbarProvier.

    import AlertContext from "../context/alert/alertContext";
    import { SnackbarProvider } from "notistack";
    
    const Alerts = (props) => {
      const alertContext = useContext(AlertContext);
      const providerRef = React.useRef();
    
      useEffect(() => {
        alertContext.msg !== "" &&
          providerRef.current.enqueueSnackbar(alertContext.msg, {
            variant: alertContext.type,
          });
      }, [alertContext]);
      return <SnackbarProvider ref={providerRef} maxSnack={4}>
           {props.children}
           </SnackbarProvider>;
    };
    
    export default Alerts;