Abnormal behavior as it shouldn't


#1

Hello there,

I have a “phone” collection. Where is stores owner, phone-number. I have template called Home and in that I have following.

Template.home.helpers({

	getdata(){

		var count = Phone.find({owner:Meteor.userId()}).count();
            console.log(count);
		if(count>0)
		{
			return true;
		}
		else
		{
			return false;
		}

	},
});

I’m calling it on Home template.

<template name="home">

	{{#if getdata}}
		<h1>Phone number exists</h1>
	{{else}}
                <h1>Phone number doesn't exists</h1>
        {{/if}}
</template>

Now the problem is that, at first it returns 0 value in console and after some milliseconds it returns 1 if phone number exists with that user owner id. Of course it will show 0 in case of no phone number associated with user but when user has phone number is first displays 0 in console and then 1. Why it’s showing 0 first ? I have tried with other collections too the behavior is same. Any help will be appreciated.

Screen shot : http://image.prntscr.com/image/71de10330bd24d5c8068e32f79253bb1.png

Thank You!


#2

It is because your template is loading before the subscription is ready.

To think about it, slow everything down.
Imagine your page loads, the template executes, your subscriptions are loading… the helper fires off once, however your subscription isn’t ready yet. So it console.log() the zero count…
Moments later the subscription completes, and the count updates… new console.log() now for the ` count.

Look into pausing while subscriptions load, or just work with the delay.


#3

Damn! Didn’t know this. Where should I subscribe the collection ? I have put in isClient function. If the current location is right then how to work with delay ?


#4

If you’re not subscribing that means you’re still running with autopublish enabled, which basically automatically publishes all your data to all your users. Best you take a look into some of the example apps to look at how they manage Publish and Subscribe - take a look at the docs and the guide too!

note - you don’t ever want to run with autopublish in the real world.


#5

I have already disabled auto publish and secure package.

Edit: I have solved it with ready() function. I checked if the subscription is ready or not. If ready then and then run the code inside the method.

Thank you very much for drawing my attention.