Kayote
Kayote

Reputation: 15627

Validate route on click and before the page-load

Within Next.js, how would I validate a route before its loaded?

As per the API docs, routeChangeStart is triggered before route change, however, I am unable to cancel the event once triggered.

  useEffect(() => {
    events.on("routeChangeStart", routerChangeHandler);
    return (() => events.off("routeChangeStart", routerChangeHandler));
  });

  const routerChangeHandler = (url) => {
    if(/* check something */){
      // stop the new page load and stay on the page
      return false;
    }
  };

Upvotes: 1

Views: 688

Answers (2)

lissettdm
lissettdm

Reputation: 13078

You can try throwing an error to cancel the navigation:

  events.on('routeChangeStart', () => {
    throw new Error('AbortError');
  });

Also you can try to dispatch routeChangeError:

 events.emit('routeChangeError');

Upvotes: 2

Yamo93
Yamo93

Reputation: 512

I think you should do something like this: Next JS: Warn User for Unsaved Form before Route Change

Upvotes: 2

Related Questions