reactjsnavigationreact-router-domonsubmitreact-toastify

Show a react-toastify toast after navigating to another page


I have this function that submits data to an API call function on submit and then with the successdata it shows a toast. As the next step I made it to navigate to another page and to show the toast. But it only navigates and doesn't show the toast.

const submitHandler = () => {
    updatePatient(
      data,
      (successData: any) => {
        toast.success(successData, {
          position: "top-right",
          autoClose: 5000,
          hideProgressBar: true,
          closeOnClick: false,
          pauseOnHover: true,
          draggable: true,
          progress: undefined,
          theme: "light",
        });
        navigate("/allpatients");
      },
      (errorData: any) => console.log(errorData)
    );
  };

Toastcontainer on navigated route

<ToastContainer
        position="top-right"
        autoClose={5000}
        hideProgressBar
        newestOnTop={false}
        closeOnClick={false}
        rtl={false}
        pauseOnFocusLoss={false}
        draggable
        pauseOnHover
        theme="light"
      />

I tried the answers of the similar questions first but didn't work. I have a toastcontainer on the page I'm navigating.

I tried removing navigation and then it works fine. But I need the navigation.

Thanks.


Solution

  • I tried a settimeout of 1ms and it works. Feels like a hack but it looks fine.

    const submitHandler = () => {
        updatePatient(
          data,
          (successData: any) => {
            navigate("/allpatients");
            setTimeout(() => {
              toast.success(successData, {
                position: "top-right",
                autoClose: 5000,
                hideProgressBar: true,
                closeOnClick: false,
                pauseOnHover: true,
                draggable: true,
                progress: undefined,
                theme: "light",
              });
            }, 1);
          },
          (errorData: any) => console.log(errorData)
        );
      };