Skip to content

Instantly share code, notes, and snippets.

@MarksCode
Last active April 13, 2024 10:04
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save MarksCode/64e438c82b0b2a1161e01c88ca0d0355 to your computer and use it in GitHub Desktop.
Save MarksCode/64e438c82b0b2a1161e01c88ca0d0355 to your computer and use it in GitHub Desktop.
return `usePrompt` capabilities from react-router
/**
* Prompts a user when they exit the page
*/
import { useCallback, useContext, useEffect } from 'react';
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom';
function useConfirmExit(confirmExit: () => boolean, when = true) {
const { navigator } = useContext(NavigationContext);
useEffect(() => {
if (!when) {
return;
}
const push = navigator.push;
navigator.push = (...args: Parameters<typeof push>) => {
const result = confirmExit();
if (result !== false) {
push(...args);
}
};
return () => {
navigator.push = push;
};
}, [navigator, confirmExit, when]);
}
export function usePrompt(message: string, when = true) {
useEffect(() => {
if (when) {
window.onbeforeunload = function () {
return message;
};
}
return () => {
window.onbeforeunload = null;
};
}, [message, when]);
const confirmExit = useCallback(() => {
const confirm = window.confirm(message);
return confirm;
}, [message]);
useConfirmExit(confirmExit, when);
}
@Vivekganga221
Copy link

Verify Github on Galxe. gid:FEtLZqZnzCz7ibteA6nkC3

@MarcusChrist
Copy link

Working! <3

@reintroducing
Copy link

Can also confirm this is working with react-router-dom v6.4.2. Thank you!

@jfreedman-eagent
Copy link

It worked for me on v6.4.2, but not in every case a navigation event occurred. It would block if the user closed the tab or tried to click a link to another page, but wouldn't block on history events. I tried listening to the popstate event as well, but to no avail.

Regardless, thanks for putting this together!

@Hubbsy
Copy link

Hubbsy commented Dec 15, 2022

This also worked for me, on v6.4.3. Thank you so much!!

@tahme
Copy link

tahme commented Dec 19, 2022

On v6.5.0 this works with useNavigate. If I trigger navigation with router.navigate (see remix-run/react-router#8599 (comment)), this doesn't work. I guess I'll wait for Prompt to come back officially now that it seems to be gaining progress.

@mike667
Copy link

mike667 commented Jan 4, 2023

Version 6.6.1 works well. Thank you!

@zadahead
Copy link

zadahead commented Jan 8, 2023

Perfect code, Thank you very much!
you even did better the chatGPT

@denchiklut
Copy link

Thanks a lot!. You can actually simplify it by using
import { unstable_useBlocker as useBlocker } from 'react-router-dom'

like this

@pabloSalva
Copy link

Thanks!! working with v6.8.1

@asmaaEbeed
Copy link

Thanks a lot, I'm searching for a week and it's only way solve the problem work with version 6.6.1 for react-router-om
Now I can reset my app settings if user does not save changes and before go to another route

@SSUBRA14
Copy link

It worked for me on v6.4.2, but not in every case a navigation event occurred. It would block if the user closed the tab or tried to click a link to another page, but wouldn't block on history events. I tried listening to the popstate event as well, but to no avail.

Regardless, thanks for putting this together!

Yes, its same for me well... Is it possible to handle browser back buttons?

@L2Develop96
Copy link

Thanks it's working perfectly ! But is there anyway to make a custom dialog instead of the standard confirm dialog?

@Niyatihd
Copy link

Hello, was anyone able to make this work with custom dialog box??

@Niyatihd
Copy link

Thanks it's working perfectly ! But is there anyway to make a custom dialog instead of the standard confirm dialog?

Did you happen to find a way???

@Niyatihd
Copy link

Niyatihd commented Jun 12, 2023

The implementation for custom dialog that worked for me,

import { useCallback, useContext, useEffect } from 'react';
import { UNSAFE_NavigationContext as NavigationContext } from 'react-router-dom';
import { useConfirmModal } from 'src/components';

const useConfirmExit = (confirmExit: (confirmNavigation: () => void) => void, when = true) => {
  const { navigator } = useContext(NavigationContext);

  useEffect(() => {
    if (!when) return;

    const push = navigator.push;

    navigator.push = (...args: Parameters<typeof push>) => {
      const confirm = () => push(...args);
      confirmExit(confirm);
    };

    return () => {
      navigator.push = push;
    };
  }, [navigator, confirmExit, when]);
};

export const usePrompt = (message: string, when = true, onContinue?: () => void) => {
  const { confirm } = useConfirmModal();

  // This is to ensure that work is saved on page accidental exit or refresh
  useEffect(() => {
    if (when) {
      window.onbeforeunload = function () {
        return message;
      };
    }

    return () => { window.onbeforeunload = null };
  }, [message, when]);

  const confirmExit = useCallback((confirmNavigation: () => void) => {
    const onConfirm = () => {
      if (onContinue) onContinue();
      confirmNavigation();
    }

    confirm.warning({
      title: '',
      description: message,
      confirmText: 'Continue',
      onConfirm,
    });
  }, [message, onContinue]);

  useConfirmExit(confirmExit, when);
};

@BustamanteMelkia
Copy link

Great job!, it works

@mayafelipe
Copy link

mayafelipe commented Sep 1, 2023

Hey @Niyatihd. How did you use the useConfirmModal, is it a context ? Could you share this implementataion please?

@CleverAtBen
Copy link

@Niyatihd

The implementation for custom dialog that worked for me,

I would be keen to see the useConfirmModal implementation too please !!

@denchiklut
Copy link

@mayafelipe and @CleverAtBen I added an example with useConfirm.

export const usePrompt = () => {
    const [isDirty, setDirty] = useState(false)
    const blocker = useBlocker(isDirty)
    const { show } = useConfirm()

    const confirm = useCallback(() => {
        if (!isDirty) return Promise.resolve(true)

        return new Promise<boolean>(resolve => {
          show({
                title: 'You have unsaved changes.',
                subtitle: 'Changes you made may not be saved.',
                confirmText: 'Confirm',
                cancelText: 'Cancel',
                onConfirm: () => resolve(true),
                onCancel: () => resolve(false)
            })
        })
    }, [isDirty, show])

    useEffect(() => {
        if (blocker.state === 'blocked') {
            confirm().then(result => {
                if (result) blocker.proceed()
                else blocker.reset()
            })
        }
    }, [blocker, confirm])

    useEffect(() => {
        if (isDirty) window.onbeforeunload = () => 'Changes you made may not be saved.'

        return () => {
            window.onbeforeunload = null
        }
    }, [isDirty])

    return { setDirty }
}

Run yarn dev or yarn spa to run the app.
Hope this will be helpfull

@dev2-piniada
Copy link

Hey @Niyatihd. can you show me how is the implementation of useConfirmModal

@denchiklut
Copy link

@dev2-piniada you can check the example from comment above. You can find useConfirm implementation there

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment