Search code examples
reactjsformsreact-hooksuse-effectreact-toastify

Show toast after a form submit


I want to submit a form and I want to reload the current page so that form gets refreshed and after refreshing I want to show the Api response in toast. When I comment out event.preventDefault(), it doesn't show toast after the reload. And when I use event.preventDefault() and manually reload the page, the toast works fine! but I want it to be automatically refreshed and show toast. Here's my code,

    const handleAddUser = async (event) => {
    event.preventDefault();
    try {
      const result = await Http.post(apiEndPoint, {
        userRole: role,
        userEmail: userEmail,
        userPassword: userPassword,
        firstName: firstName,
        lastName: lastName,
        address: address,
      });
      localStorage.setItem("res", "success");
      localStorage.setItem("success", result.data);
      console.log("proper", props);
    } catch (ex) {
      localStorage.setItem("res", "err");
      localStorage.setItem("err", ex.response.data);
    }
  };

and here's my useEffect hook,

    useEffect(() => {
    const response = localStorage.getItem("res");
    const result = localStorage.getItem(response);
    if (response && response === "success") {
      toast.success(result);
      localStorage.removeItem("res");
    } else if (response && response === "err") {
      toast.error(result);
      localStorage.removeItem("res");
    }
  }, []);

Solution

  • That is because if you remove event.preventDefault(), your page got reload before it has a chance to send a request and set to the localStorage

    A solution is to keep event.preventDefault() and put window.location.reload() at the end of your handler like so:

    const handleAddUser = async (event) => {
      event.preventDefault();
      try {
        const result = await Http.post(apiEndPoint, {
          userRole: role,
          userEmail: userEmail,
          userPassword: userPassword,
          firstName: firstName,
          lastName: lastName,
          address: address,
        });
        localStorage.setItem("res", "success");
        localStorage.setItem("success", result.data);
        console.log("proper", props);
      } catch (ex) {
        localStorage.setItem("res", "err");
        localStorage.setItem("err", ex.response.data);
      }
      window.location.reload();
    };