question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Route cancellation

See original GitHub issue
  • I have searched the issues of this repository and believe that this is not a duplicate.

Expected Behavior

A method in router API that allows aborting upcoming route change.

Current Behavior

Right now router exposes abortComponentLoad method but it seems to be designed only for internal use and it doesn’t work if it’s called in routeChangeStart handler. It works only after this piece of code was executed:

async fetchComponent (route, as) {
  let cancelled = false
  const cancel = this.componentLoadCancel = function () {
    cancelled = true
  }

Workaround:

Router.ready(() => {
  Router.router.on('routeChangeStart', () => {
    setTimeout(() => {
      Router.router.abortComponentLoad();
    });
  });
});

Context

This is useful for example when building complex forms and we want to warn a user before he leaves the page without submitting.

Your Environment

ANY

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:105
  • Comments:59 (4 by maintainers)

github_iconTop GitHub Comments

71reactions
lcswillemscommented, Jun 10, 2021

Even with this, I can’t get your code working. But, I found another way to do it that works for me:

const routeChangeStart = url => {
  if (Router.asPath !== url && unsavedChanges && !confirm(message)) {
    Router.events.emit('routeChangeError');
    Router.replace(Router, Router.asPath, { swallow: true });
    throw 'Abort route change. Please ignore this error.';
  }
};

The full code in TypeScript (I rewrote @Betree solution with hooks and by removing intl, etc…):

import { useEffect } from 'react';
import Router from 'next/router';

export const useWarnIfUnsavedChanges(unsavedChanges: boolean) => {
  const message = 'Do you want to leave?';

  useEffect(() => {
    const routeChangeStart = url => {
      if (Router.asPath !== url && unsavedChanges && !confirm(message)) {
        Router.events.emit('routeChangeError');
        Router.replace(Router, Router.asPath);
        throw 'Abort route change. Please ignore this error.';
      }
    };

    const beforeunload = e => {
      if (unsavedChanges) {
        e.preventDefault();
        e.returnValue = message;
        return message;
      }
    };

    window.addEventListener('beforeunload', beforeunload);
    Router.events.on('routeChangeStart', routeChangeStart);

    return () => {
      window.removeEventListener('beforeunload', beforeunload);
      Router.events.off('routeChangeStart', routeChangeStart);
    };
  }, [unsavedChanges]);
};

then add:

useWarnIfUnsavedChanges(unsavedChanges)

at the beginning of your page/component.

Please, let me know if there is any issue with my code or if you see how to improve it.

44reactions
davidalejandroaguilarcommented, Mar 29, 2021

I wonder if we’ll ever have an official API for this, it’s been almost 4 years.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Route Terms and Conditions
Cancellation of the Agreement must be in writing and received by Route at least five (5) days before the end of the month....
Read more >
Cancel route | Navigation services | Support and legal ...
To simply cancel a route, tap on Cancel (the cross) in the navigation view. You can also delete ongoing directions as follows: Tap...
Read more >
bus trips cancellations
BUS TRIPS CANCELLATIONS ... Routes and Schedules · SacRT BusTracker · Google Trip Planner · Accessible Services · Holiday Schedule · Service Alerts ......
Read more >
Route cancellation - Sygic GPS Navigation for iOS - 16.4.
To cancel the current route, please open the Quick menu and tap on Cancel Route button.
Read more >
Route cancellation · Discussion #32231 · vercel/next.js
_cancel = false let err = new Error('Abort') err.cancelled = true throw err } } // set global._cancel = true whenever you want...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found