Where is the correct place to fetch data from the database?

Hi,

I am using flow router and blaze.
I am calling a meteor method to get info from the database.
Which is the correct place ?
Template.Page_practice.onCreated or Template.Page_practice.onRendered ?
and why ?

I prefer to put data loading and validation in onCreated, because it happens earlier and reduces the delay until that data is available to the template

3 Likes

Do you know how to wait for Meteor.logginIn() ?
I am always redirected when hitting the refresh button on the browser:

let adminRoutes = FlowRouter.group({
  prefix: '/admin',
  triggersEnter: [function(context, redirect) {
    let redirection = false;
    if (!Meteor.loggingIn() && !Meteor.userId()) {
      redirection = true;
    } else {
      let user = Meteor.user();
      redirection = !user.isAdmin;
    }
    if (redirection) {
      redirect('/');
    }
  }],
  titlePrefix() {
    return 'MassEducationWeapon | ';
  }
});

I’ve just got them as a group:

const loggedInRoutes = FlowRouter.group({
  name: 'loggedIn',
  triggersEnter: [
    (context, redirect) => {
      if (!Meteor.userId() && !Meteor.loggingIn()) {
        const current = FlowRouter.current();

        if (current.route.name !== 'login') {
          RouterState.set('redirectAfterLogin', current.path);
          redirect('login');
        }
      }
    },
  ],
});

For admin roles I’m using alanning:roles, which means having to wait for the roles subscription before routing:

// Pause FlowRouter until Roles information is ready
FlowRouter.wait();
  Tracker.autorun(() => {
  // if the roles subscription is ready, start routing
  // there are specific cases that this reruns, so we also check
  // that FlowRouter hasn't initalized already
  if (!FlowRouter._initialized && Roles.subscription.ready()) {
    FlowRouter.initialize();
  }
});
// loggedInRoutes definition here
const adminRoutes = loggedInRoutes.group({
  prefix: '/admin',
  triggersEnter: [
    function(context, redirect) {
      if (!Roles.userIsInRole(Meteor.user(), ['admin'])) {
        redirect('root');
      }
    },
  ],
});

Thanks a lot.
FlowRouter.wait(); is what I was looking for.
Where do you call it ?

By the way, redirect(‘root’); I understand that the redirect function only works with urls and not with route names.

I call it at the top of my routes file

I’m using ostrio:flow-router-extra, so redirect behaves exactly like FlowRouter.go. ie. can point to route names: https://github.com/VeliovGroup/flow-router/blob/master/docs/full.md#triggersenter

1 Like

Thanks a lot, you saved me with this code.
I was blocked with this for a month.

1 Like