React-router: asynchronous operations in routerWillLeave

Created on 23 Oct 2015  路  12Comments  路  Source: ReactTraining/react-router

The problem I have is that in routerWillLeave function, I can't perform an asynchronous operation before I call return.

This is in 1.0.0-rc, maybe this can be done in some other way or it is supported but I don't know how.

Any help?

Most helpful comment

Yes, that is true. But that is an unnecessary restriction for a SPA route transition (except to simplify the API).

All 12 comments

The leave hooks are only for blocking transitions: https://github.com/rackt/react-router/issues/1938#issuecomment-140405611

@taion Then how do I do an async operation to determine if I want to block transition or not?

Why would you need to? Transition blocking should be a synchronous function of the current state of the view.

@taion The state of the view determines if I need to have an api call to further determine if the transition need to be blocked or not. Given this call is async by nature and it's not used for the state of the view that user is on, routerWillLeave will be a perfect place for it.

That's not going to be supported - window.onbeforeunload doesn't support anything of the type so it doesn't make any sense to add it here.

@taion Not a huge issue, but the use case I had for using async onLeave hooks is to use a custom-styled dialog box consistent with the rest of the site's dialog boxes. And there is no way to synchronously await user input from a dialog except with confirm(), which looks super ugly.

There's no way to show anything else when leaving the page, though.

Yes, that is true. But that is an unnecessary restriction for a SPA route transition (except to simplify the API).

I know this is closed, but totally agree with @idolize. I'd like to use a custom confirm dialog like this, but the current API won't support it.

@taurose That link seems to assume I'm using history directly. Are you saying to do this I'd stop using React Router's BrowserHistory and instead:

  1. Install history
  2. Pass history's router to my <Router> component at my app's entry point.

I know history is used behind the scenes, but I'm unclear what the implications are of using history directly with React Router.

You can pass your own history to Router. Make sure to import the "useRouterHistory" from react router as your base function

Was this page helpful?
0 / 5 - 0 ratings

Related issues

winkler1 picture winkler1  路  3Comments

Waquo picture Waquo  路  3Comments

yormi picture yormi  路  3Comments

andrewpillar picture andrewpillar  路  3Comments

nicolashery picture nicolashery  路  3Comments