tmeasday / meteor-router

MIT License
366 stars 76 forks source link

Routes called twice? #99

Closed daslicht closed 11 years ago

daslicht commented 11 years ago

Hi, i have the following Route:

'/test': { 
        to:'masterDetail',
        and: function(){
           var mostRecentPost = Posts.findOne({}, { sort: { date: -1 }});

                console.log('show blog newest entry: ', mostRecentPost);  0
        }
    }

When I call it I get the following message in my console:

show blog newest entry:  undefined router.js:28
show blog newest entry:  Object {_id: "hHtwqdW69cpbmjzKR", date: 1371646889506, detailsId: "hHtwqdW69cpbmjzKR", headline: "another new"} router.js:28

Why is the Route called twice ? and why is the first 'mostRecentPost' undefined?

tmeasday commented 11 years ago

Because the route initially runs while the subscription is still loading from the server. Then, once the data is available, it reactively re-runs with the correct data.

daslicht commented 11 years ago

so its not a good idea to query the db in my routes ?

daslicht commented 11 years ago

Lets say i have this route: '/blog/:_postId': as long as the client calls it with parameters anything is fine

now like to have another router which reacts to just /blog but calls automatically the most recent post So my idea was to just query the db and redirect to my '/blog/:_postId': route. Whats teh best way to solve this, please?

tmeasday commented 11 years ago

You need to check whether the subscription is ready (you can use the ready() method on the subscription handle).

So something like:

if (postsSub.ready()) {
  var recentPost = Posts.findOne(...);
} else {
  return 'loading';
}
daslicht commented 11 years ago

thank you

daslicht commented 11 years ago

And postsSub would be Meteor.subscribe('postsSub'); ?

I tried it i get postsSub is undefined

tmeasday commented 11 years ago

Something like postsSub = Meteor.subscribe('posts');

daslicht commented 11 years ago

:+1:

daslicht commented 11 years ago

Very nice Its now working !!! Thank you very much !