Using PopStateEvent correctly

47 Views Asked by At

I have the following code implemented, where when users press the back/forward button of the browser, it will trigger the PopStateEvent to do an exit confirmation, where if the users confirm their exit, exitToServer() function will be called. exitToServer() function contains HTTP request to server to inform them that this particular userID is going to exit.

// implementation of PopStateEvent
useEffect(() =\> {
        console.log("Popstateevent useeffect called");

        const handlePopState = (event: PopStateEvent) => {
            console.log("Popstateevent occurred");
            
            const exitConfirmation = window.confirm('Leaving so soon? Chat will be lost.');
            if (exitConfirmation) {
                exitToServer();
            } else {
                // Prevent leaving the page
                event.preventDefault();
                // Restore the URL to the current one
                window.history.pushState(null, document.title, window.location.href);
            }
        };
    
        window.addEventListener('popstate', handlePopState);
        console.log("Attached event")
    
        return () => {
            console.log("popstate event cleanup called")
            window.removeEventListener('popstate', handlePopState);
        };
    }, []);
// exit to server function that works with BeforeUnloadEvent
const exitToServer = async () =\> {

        const dataToSend = {
        username: usernameToSend
        };
    
        console.log("sending exit to server")
    
        try {
            await fetch(`http://${host}:${port}/exit`, {
            method: 'DELETE',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(
                dataToSend)
            });
    
            console.log(dataToSend);
    
            const exitConfirmation = 'Leaving so soon?';
            return exitConfirmation;
        }
        catch (error) {
            console.error('Error sending message:', error);
            throw error;
        }
    }

Here is my implementation of the BeforeUnloadEvent that is implemented on top of the PopStateEvent: (It only works for refresh and close tab button)

    useEffect(() => {
        const handleBeforeUnload = (event: BeforeUnloadEvent) => {

            exitToServer();

            const exitConfirmation = 'Leaving so soon? Chat will be lost.';
            event.returnValue = exitConfirmation;
            return exitConfirmation;
        };

        window.addEventListener('beforeunload', handleBeforeUnload);

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

The UseEffect() does not work as when I tried logging to the inspector, I realize that the PopStateEvent was never triggered when i activate the browser's back button. Is there any way to go about this issue? Thanks.

0

There are 0 best solutions below