Search code examples
javascriptmeteoriron-router

How to wait for subscribtion Iron Router with auto-publish?


I'm actually developping a WebApp with Meteor. Since i'm more focused on UI and specs than being ready for production and look at security issues.(would do that later, after I've done a good PoC).

I would like to keep the autopublish and insecure packages (damn that's cool to go quick).

I'm bumping into an annoying issue with Iron Router. The problem is pretty simple, but I'cannot find a way to make it work properly. Sometime data return randomly undefined.

Router.route('/stuff/:_id', {
  name: 'stuff',
  template: 'stuff',

  data: function(){
    var stuff = Stuffs.findOne(this.params._id);
    console.log("stuff: ", stuff);
    return {headerTitle: stuff.name, stuffData: stuff};
  },
  action: function(){
    this.render();
  }
});

It's actually not that random, I guess something like this happen:

Working well when I hit this route from link from the App (I guess the data is ready)

But on page refresh, or on naviguate by the url, I could have this annoying undefined.

Everything is autopublish, so it's would be strange to use a waitOn into my route...

Does someone hit the same problem and got a solution?


Solution

  • Get it! Was simpler than I expected!

    Related this issue: https://github.com/iron-meteor/iron-router/issues/295

    Obviously Meteor cursor are reactive, finally I just have to do:

    Router.route('/stuff/:_id', {
      name: 'stuff',
      template: 'stuff',
    
      data: function(){
        var stuff = Stuffs.findOne(this.params._id);
        if(stuff){
            console.log("stuff: ", stuff);
            return {headerTitle: stuff.name, stuffData: stuff};
        }
      },
      action: function(){
        this.render();
      }
    });
    

    Testing if stuff is undefined before doing anything, so stuff is not used -> no errors. On update the hook will be rerun, done.

    That's it. Pretty cool and simple, I don't even think about that!