[iron-router] Router.go not working from event but ok from console

I have this piece of code inside a template event function (it is a pagination button), and when it is triggered, the url flicks like the url is changing, but it immediately comes back to the current URL and the template remains the same. No errors are thrown in the console.

'click [data-action=next]': function(e, t) {
    Router.go('city.cards.page', {city: 'new-york', page: 3})
}

The funny thing is, when I execute the exact same code from the console instead of pressing the button, it works perfectly.

Here’s the route I’m using

Router.route('/cities/:city/cards/:page', {
    subscriptions: function() {
        this.subscribe('reports', {page: this.params.page}).wait();
    },
    name: 'city.cards.page',
    template: 'City',
    action: function() {
        Session.set('selectedSection', 'cards')
        if (this.ready()) {
            this.render()
        } else {

        }
    }
});

Any ideas? Thanks!

What happens when you log something in that action? Is the action actually being fired?

(I appreciate your description indicates something’s happening, but I figure it’s best to rule out that action isn’t being triggered by something else)

try and add e.preventDefault() to your event before the Router.go.. bit.

3 Likes

thank you, such a simple solution. I always remember to add it when submitting a form, but clicking an anchor :facepalm:

e.preventDefault() ftw!

sure, glad i could help :smile:

Another way to fix it is by deferring the call to a future tick with setTimeout or awaiting something in the line prior if using async functions.

setTimeout(function() {
  Router.go(...)
}, 0)

// or

await Promise.resolve()
Router.go(...)

This is completely unexpected though. I wonder if iron:router can fix it…

1 Like