-1

I recently transitioned from using Next.js to React.

I'm currently using react-router-dom version 6.14.2.

On my detail page, when data has been modified, I want to trigger an antd Modal if the previous data and the modified data are different. When the user attempts to navigate back, the Modal should appear. Clicking "ok" should take them to the previous page, while clicking "cancel" should prevent the navigation.

However, as I've researched, even though it's the same v6 version, it seems there have been many changes in react-router-dom. Features like usePrompt are no longer available, and it seems I can't use UNSAFE_NavigationContext either.

I'm feeling quite frustrated. Is there any solution to this?

How can I implement a back-navigation confirmation in react-router-dom similar to my Next.js logic?

I've been searching for various custom hooks, but most of them seem to be outdated or prior to 2023. Do I need to downgrade?

Below is the code I used in Next.js to handle back-navigation:

  useEffect(() => {
    const handleBeforeUnload = (e: BeforeUnloadEvent) => {
      if (JSON.stringify(prevValues) !== JSON.stringify(form.getFieldsValue(true)) ) {
        e.preventDefault();
        e.returnValue = '';
      }
    };
    router.beforePopState(({ url, as }) => {
      if (as !== router.asPath) {
        if (JSON.stringify(prevValues) !== JSON.stringify(form.getFieldsValue(true))) {
          Modal.confirm({
            title: 'confirm_description',
            content: 'confirm_description_request',
            okText: 'confirm',
            cancelText: 'cancel',
            onOk: () => {
              router.replace(url, undefined, { shallow: true });
            },
            onCancel: () => {
          
              window.history.pushState({}, '', router.asPath);
              router.replace(router.asPath);
            },
          });
          return false;
        } else {
          router.replace(url, undefined, { shallow: true });
          return false;
        }
      }
      return true;
    });
    if (JSON.stringify(prevValues) !== JSON.stringify(form.getFieldsValue(true))) {
      window.addEventListener('beforeunload', handleBeforeUnload);
    } else {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    }

    return () => {
      router.beforePopState(() => true);
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [router, prevValues, form.getFieldsValue(true)]);

I aim to implement similar functionality using react-router-dom. Any assistance would be greatly appreciated.

ian
  • 1
  • 1
  • 1
    It's unclear what `react-router-dom` code you are using since you didn't include a [mcve], but does this help answer your question? https://stackoverflow.com/q/75135147/8690857 – Drew Reese Aug 21 '23 at 23:56

0 Answers0