Home > Enterprise >  React-toastify duplicating toast
React-toastify duplicating toast

Time:11-24

I have a mods page in my app which only moderators and administrators should be able to access. If a person tries to access it by directly typing the URL I have some logic that would redirect them.

import { useHistory } from "react-router";
import createNotification from "../../../addNotification";
import getRole from "../../../authentication";

const ModHome = () => {
    const history = useHistory();
    const role = getRole();

    if (!["administrator", "moderator"].includes(role)) {
        createNotification("You are not a moderator", "error");
        history.push("/admin-login");
    }

    return (
        <div>
            <h1>Mod page</h1>
        </div>
    )
}

export default ModHome

The logic works fine. I get redirected to the login page but for some reason this happens enter image description here

I already checked and the toasts have different IDs and the function gets called only once so why am I getting 2 notifications?

Update: Here's the createNofication code:

import {toast} from "react-toastify";

export default function createNotification(message, type) {
    const options = {
      position: "top-right",
      autoClose: 5000,
      hideProgressBar: false,
      closeOnClick: true,
      pauseOnHover: true,
      draggable: true,
      progress: undefined,
    };
    switch(type) {
      case "success":
        toast.success(message, options);
        break;
      case "warning":
        toast.warn(message, options);
        break;
      case "error":
        toast.error(message, options);
        break;
      case "info":
        toast.info(message, options);
        break;
    }
}

CodePudding user response:

Why do you believe that the function is being called only once? Running this if code in the body of your component will cause its execution everytime that the component renders or rerenders, so I believe that this function is being called multiple times.

If you wrap it with a useEffect with an empty dependency array you will probably stop seeing the duplicate.

  • Related