choo icon indicating copy to clipboard operation
choo copied to clipboard

Docs: Code to listen for 'navigation' change does not output written behavior

Open as-dr opened this issue 7 years ago • 5 comments

Expected behavior

In the Choo docs on Routing, in the section "Listening for Route Changes" implementing:

var html = require('choo/html')
var choo = require('choo')
var app = choo()

var app = choo()
app.use((state, emitter) => {            // 1.
  emitter.on('navigate', (route) => {    // 2.
    console.log(`Navigated to ${route}`) // 3.
  })
})

Should return a console message "Navigated to [insert route here]

Actual behavior

This code snippet instead returns a console message "Navigated to undefined"

Steps to reproduce behavior

  1. Add in code as written in the docs (and reproduced above)
  2. Click through / navigate between two separate routes.
  3. Observe the console message.

as-dr avatar Feb 13 '18 09:02 as-dr

Here's the link to the routing documentation: https://github.com/choojs/website/blame/49f3b8d4aabbadaf67c13854fb3ce680a57374dd/content/docs/routing/index.md#L340

I don't think that this ever worked in v6... maybe in earlier versions. The route is available on app.state.route.

marcbachmann avatar Feb 15 '18 04:02 marcbachmann

if we're considering changing the api here (to, from) would be cool.

bates64 avatar Feb 15 '18 06:02 bates64

yeah, knowing the previous route would be really useful!

goto-bus-stop avatar Feb 15 '18 10:02 goto-bus-stop

We won't have access to the previous state anymore with the current setup. Should we only pass specific properties?

... I'm also not sure how we should differentiate the state in before and after hooks. This needs a proper proposal for all events/behaviors first. Here's also some comment regarding that: https://github.com/choojs/choo/pull/613#discussion_r158749713

marcbachmann avatar Feb 15 '18 11:02 marcbachmann

re: knowing the previous route:

How about adding a previousRoute property to the state? We could copy it over when we _matchRoute:

 Choo.prototype._matchRoute = function (locationOverride) {
   var location, queryString
   if (locationOverride) {
     location = locationOverride.replace(/\?.+$/, '')
     queryString = locationOverride
   } else {
     location = this._createLocation()
     queryString = window.location.search
   }
   var matched = this.router.match(location)
   this.state.href = location
   this.state.query = nanoquery(queryString)
+  this.state.previousRoute = this.state.route
   this.state.route = matched.route
   this.state.params = matched.params
   this.state._handler = matched.cb
   return this.state

I'm looking at animating route transitions and having access to previous route (somehow, doesn't have to be this way) would be super useful.

As for the docs reflecting actual behavior I made a small pr here: https://github.com/choojs/website/pull/61

kareniel avatar Feb 25 '18 21:02 kareniel