0

I want to warn the user when some changes are made by the user and he tries to leave the page. This is my react code it's working fine on page reload and or when try to close the tab. but when I try to goto another page this doesn't work.

useEffect(() => {
        const handleBeforeUnload = (e: any) => {
            console.log('123');
            if (hasUnsavedChanges) {
                e.preventDefault();
                e.returnValue = '';
                                return e.returnValue;
            }
        };

        // Attach the event listener
        window.addEventListener('beforeunload', handleBeforeUnload);

        // Clean up the event listener when the component unmounts
        return () => {
            window.removeEventListener('beforeunload', handleBeforeUnload);
        };
    }, [hasUnsavedChanges]);
Abdul Rehman
  • 222
  • 1
  • 5
  • 1
    This might help you https://stackoverflow.com/a/49163569/1283345 – Nooruddin Lakhani May 09 '23 at 07:17
  • this is for react-router v4 i am using v6 – Abdul Rehman May 09 '23 at 07:32
  • 1
    Checkout these for v6 https://stackoverflow.com/a/75139360/1283345 and https://github.com/remix-run/react-router/issues/8139 – Nooruddin Lakhani May 09 '23 at 07:39
  • 2
    the beforeunload triggers when you hard navigate to another page, with react router the window is not unloading so the event is not dispatched that you are listening for now, I think @NooruddinLakhani s answer is what you need. – Lars Vonk May 09 '23 at 08:28
  • Yeah, I tried the example and am getting the same error: useBlocker must be used within a data router. I tried to change it but doing something wrong as I am not a react expert. – Abdul Rehman May 09 '23 at 08:44

0 Answers0