wesleytodd / nighthawk

A wrapper around Express' router for the browser
ISC License
55 stars 7 forks source link

How to programatically trigger route change? #6

Closed ynonp closed 7 years ago

ynonp commented 7 years ago

Should I use _processRequest ? Or is there another way?

wesleytodd commented 7 years ago

I would just use the browsers history api. Nighthawk just watches for changes and responds accordingly. Let me know if I am misunderstanding your question.

ynonp commented 7 years ago

That was my first attempt but it seems not to work. I put a breakpoint in Router.prototype._processRequest and from console called history.pushState({}, '/', '/').

Breakpoint is not hit AND no route change happens (url is changed though)

wesleytodd commented 7 years ago

Yep, looks like you are right. I could have sworn I had done this before, but I guess not. My preference would be to not use _processRequest, and to add a method like changeRoute for this.

Can you provide more context for your usage? I just want to make sure we get the best solution.

ynonp commented 7 years ago

Sure - consider navigating after Ajax request:

  1. User clicks button
  2. JS calls xhr.send()
  3. In callback I need to navigate to success or error URL based on the response

The best solution should let me trigger navigation without keeping a reference to the router object (via some function directly on Router)

wesleytodd commented 7 years ago

Cool, yep, I think this is a good use case to support. Unfortunately after doing some research the only ways to do with with a call to history.pushState are patching the method, or checking the url on a poll. Neither of which are good IMO.

I am guessing I have not hit a use case like this because I use React in most of my apps and handle this kind of stuff without a route change.

For now _processRequest will work for sure, but I think a PR which changes _processRequest to changeRoute is better. We could even just alias it. If you want to do this I would merge and release right away. If not, I can whip it up since it is about a 5 second change.

wesleytodd commented 7 years ago

What do you think of that addition?

ynonp commented 7 years ago

I just forked the repo to create a PR, but you were faster so that's cool too :)

wesleytodd commented 7 years ago

Hahah, sorry :)

Does that work for you? If so I will publish the new version now.

ynonp commented 7 years ago

It's awesome. Thanks! Exactly what I needed

wesleytodd commented 7 years ago

https://www.npmjs.com/package/nighthawk

1.4.0 published