Home > Enterprise >  React toastify is not working , when page is redirect to another page. But it is working on same pag
React toastify is not working , when page is redirect to another page. But it is working on same pag

Time:10-07

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,

    });
}

CodePudding user response:

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

  • Related