choojs / choo

:steam_locomotive::train: - sturdy 4kb frontend framework

Home Page:https://choo.io/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

as-dr opened this issue · 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.

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.

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

yeah, knowing the previous route would be really useful!

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: #613 (comment)

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: choojs/website#61