0

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");
    }
  }, []);
Ryan Le
  • 7,708
  • 1
  • 13
  • 23
Saadi
  • 121
  • 1
  • 8
  • Just put `window.location.reload();` before the `localStorage.setItem("res", "success");` and keep `event.preventDefault();` as it is. – Surjeet Bhadauriya Sep 14 '21 at 11:02
  • Amazing, thanks it works now... I tried many times props.history.push() and window.location.reload() but the mistake was that i was trying after the line localStorage.setItem('res','success'); – Saadi Sep 14 '21 at 11:10

1 Answers1

0

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();
};
Ryan Le
  • 7,708
  • 1
  • 13
  • 23