2

I use react-toastify for toast notification, but it is not working when my page is redirec to another page.

It is not working mydata is save to the data base. It is working when my page is not redirect.

const [email, setEmail] = useState("");
const [password, setPassword] = useState("");

const loginUser = async (e) => {
    e.preventDefault();
    const res = await fetch("/signin", {
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify({ email, password }),

    });

    const data = await res.json();
    if (res.status === 422 || !res) {
        warningAlert();
        console.log(res);
        console.log("Invalid Credentials")
    } else {
        successAlert();
        dispatch({ type: "USER", payload: true });
        // console.log(res);
        history.push("/");

    }
}

the above code is for login. here notification is not working in else condition, but working in if condition.

Above Mentioned alert

    const successAlert = () => {
    // window.alert("Invalid Credentials");
    toast("User logged in successfully", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: false,
        draggable: true,
        progress: undefined,

    });
}


    const warningAlert = () => {
    // window.alert("Invalid Credentials");
    toast.error("Invalid Credentials", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: false,
        draggable: true,
        progress: undefined,

    });
}
MAYANK THAKUR
  • 773
  • 1
  • 6
  • 11

2 Answers2

7

you have to use <ToastContainer/> in root of you project so that this container is accessible from all the pages. and then call the fucntion

Official Doc

swapnil gautam
  • 319
  • 2
  • 9
2

In my case, It was window.location.href = '/user' which i was using for going to homepage after user is created. This will cause whole application to reload(reset) and thus Notification will not work regardless of where you keep your <ToastContainer/> component.

Make sure, you are using react-router methods(history.push or navigate) for route change.

Firoj Siddiki
  • 1,649
  • 1
  • 20
  • 22