FindOne() doesn't work on refresh


#1

Hi,

I have a basic collection, that i load on creating template in a reactive dict :

import { ColContact } from '/imports/api/contact.js';

var dict = new ReactiveDict('edit');

Template.contact_admin.onRendered(
	function () {
		var page = ColContact.findOne();

		dict.set('page', page);
	}
);

Then i use it in a basic helper :

Template.contact_admin.helpers({
	Page() {
		page = dict.get('page');
		return page;
	}
});

The strange thing is that it works when i follow a route (click on a link that use pathFor of FlowRouter) but if i reload the page (F5) or type address in navigator bar, i got undefined from ColContact.findOne().

I know i should use publish&suscribe and i will do it later, maybee it will resolve the bug. But i have no idea what i am doing wrong for the moment.

Any Idea ?
Thanks for your time !


#2

If you continue to work with Meteor, you will learn that everything is about timing. For instance, if your app is looking for data from the database before the data is ready, you will run into the type of issue you are posting about. You can leverage the power of an autorun, which will update the value when the data coming down the wire causes an invalidation.

Also, you should try to scope your variables to a template instance.

import { ColContact } from '/imports/api/contact.js';

// Scope your reactiveDict to the template
Template.contact_admin.onCreated(function() {
  this.dict = new ReactiveDict();
});

Template.contact_admin.onRendered(function() {
  let self = this;
 
 // You can use an autorun function that will rerun when the data is ready
  self.autorun(function() {
    let page = ColContact.findOne();

    // Refer to the reactiveDict you scoped to the template in the onCreated
    self.dict.set('page', page);
  });
});

// Refer to your scoped dict in a helper by using Template.instance()
Template.contact_admin.helpers({
  Page() {
    let page = Template.instance().dict.get('page');
    return page;
  }
});

#3

Hi,

Thanks alot for your awnser, i thought the problem was data unready but didn’t know how to treat it.

Thanks again.