Do some logic based on propmt in React JS

47 Views Asked by At

I want to show a prompt alert when user wants to close or refresh the page in a specific component in react js and based on confirming the refresh or the closing window do some different logic . here is my code that an AI recommond but it didnt worked for me ! how to fix that ?

      function MyComponent() {
          useEffect(() => {
            const handleBeforeUnload = (event) => {
              event.preventDefault();
        
              const confirmationMessage = "Are you sure you want to leave this page?";
              event.returnValue = confirmationMessage;
        
              if (window.confirm(confirmationMessage)) {
                // Logic to execute when the user clicks "OK" (Yes)
                console.log("User clicked Yes");
                // Perform your desired logic here for "Yes" response
              } else {
                // Logic to execute when the user clicks "Cancel" (No)
                console.log("User clicked No");
                // Perform your desired logic here for "No" response
              }
            };
    
        window.addEventListener("beforeunload", handleBeforeUnload);
    
        return () => {
          window.removeEventListener("beforeunload", handleBeforeUnload);
        };
      }, []);

1

There are 1 best solutions below

0
Akeel Ahmed Qureshi On

Try this :

useEffect(() => {
    const handleBeforeUnload = (event) => {
     
      const confirmationMessage = "Are you sure you want to leave this page?";
      event.returnValue = confirmationMessage;
    };

    const handleUnload = () => {
     
      console.log("User clicked No");
      
    };

    window.addEventListener("beforeunload", handleBeforeUnload);

    window.addEventListener("unload", handleUnload);

    return () => {
      window.removeEventListener("beforeunload", handleBeforeUnload);
      window.removeEventListener("unload", handleUnload);
    };
  }, []);