I have the following function that handles back button trigger on the browser:

useEffect(() => {
        let isOnce = false;
        const handlePop = (update: Update) => {
            if (usernameToSend && !isOnce && update.action === 'POP') {
                if (window.confirm("Leaving so soon? Chat data will be lost.")) {
                    console.log("before exitToServer");
                    isOnce = true;
                    exitToServer();
                }
                else {
                    isOnce = false;
                }
            }
        };
        if (!isOnce) {
            history.listen(handlePop);
        }

    }, [usernameToSend]);
    

I would like to prevent navigation to the previous page until the user confirms their exit as this affected the else statment in handlePop. When the user presses the back button, the window's confirmation appears and when i press cancel it navigates back to the previous page. I need the current page to stay rendered when users press the cancel button.

The reason why i implemented the isOnce variable is because exitToServer awaits the response from the HTTP request. Before implementing the isOnce variable, the window.confirm pop up will be triggered continuously, after I had clicked on either OK or Cancel button. I am not sure if the cause of the continuous trigger was due to the exitToServer function..

Do let me know if any additional information should be attached. Thank you.

0

There are 0 best solutions below