Search code examples
javascriptmeteoriron-router

Meteor - Page refresh causes flicker when fetching data for router


If I refresh a meteor page that is using a data query in the iron-router setup, the page loads the template but with no data, then shows the loading template, then shows the page with the data. I want to avoid the page flicker that is happening. This is my router code:

this.route('/stories/:_id', function () {
    if (!Meteor.user() && !Meteor.loggingIn()) {
        Router.go('home');
    } else {
      var story = Stories.findOne({ _id: this.params._id });
      this.render('showStory', { data: story });
    }
});

I've also tried this setup and moved the logged in validation to an onBeforeAction.

this.route('showStory', {
    path: '/stories/:_id',
    data: function () {
        return Stories.findOne({ _id: this.params._id });
    }
});

When I refresh the page with this setup, I see my 404 page, then the loading template, then the correct template with data.


Solution

  • Try with this.

    Router.map(function () {
      this.route('showStories', {
        path: '/stories/:_id',
        waitOn: function(){
            return Meteor.subscribe("Stories"); //we make de subscription here
        },
        data: function(){
          if(! Meteor.user()){
            this.render('/') //or sign-up template whatever template you want if user its not loged in
          }else{
    return Stories.findOne({_id: this.params._id});
          }
        }
      });
    }); 
    

    Already Tested and its working