Search code examples
reactjsmaterial-uireact-hookssweetalertuse-effect

React Hook useEffect has missing dependencies: 'classes' (Material-ui styles and react-bootstrap-sweetalert)


I'm having this warning: "React Hook useEffect has missing dependencies: 'classes.button' and 'classes.warning'."

The issue here is that, according to the recommended usage of react-bootstrap-sweetalert, I should set SweetAlert component in state (I don't know if this is a good practice, but is how they suggest to use it).

import { makeStyles } from "@material-ui/core/styles";
import styles from "assets/jss/views/Alerts";
const useStyles = makeStyles(styles);

export default function Alerts() {
  const [alert, setAlert] = useState(null);

  useEffect(() => {
    fetch('api').then(res => res.json()).then(data => setData(data))
      .catch(err => {

        setAlert(
          <SweetAlert
            style={{ display: "block", marginTop: "-100px" }}
            title="Error"
            onConfirm={() => {setAlert(null); setLoading(false)}}
            onCancel={() => {setAlert(null); setLoading(false)}}
            confirmBtnCssClass={classes.button + " " + classes.warning} // HERE!
          >
            error
          </SweetAlert>
        )

      })
  }, [])

  const classes = useStyles();
  return (
    <div>
     {alert}
     ...
    </div>
  )
}

I have multiple alert components and that is why they recommend that usage. I'd like to know the proper way to solve this.


Solution

  • If you have a classes object outside of your useEffect() which holds your button styles, then you should pass in your classes object as a dependency:

    useEffect(() => {
      ...
    }, [classes]);
    

    Otherwise, you can just hard code the button classes:

    confirmBtnCssClass={'btn btn-warning'}