Hey, I have a problem because I need to wait until data is ready, but I subscribe in onCreated method and I still dont have any data in onRendered method.
I want to wait until data is ready and show a {{>Spinner}} until load data.
Here I do the subscription on client:
`Template.statsClient.onCreated(function statsClientCreated() {
this.autorun(() => {
this.subscribe('statsByClient');
});
});`
Then, I find Stats on client:
Template.statsClient.onRendered(function () {
var stats = Stats.find();
var arrayStats = stats.map(function (stat) {
return stat.weight;
});
});
But I dont have any data :S
How can I wait until data is ready to be read?
Thx
onCreated
and onRendered
are not reactive contexts. That means that your find
will only ever run once - and most likely too quickly for the data to have arrived over the wire.
Depending on what you want to achieve, you could solve this in different ways.
Firstly, if you are doing this in a template, I assume it’s because you are rendering the results on the screen. In which case, the simplest solution may be to just use a template helper. Helpers provide a reactive context, so will re-run as needed until all data is available.
Alternatively, your subscription returns a “subscription handle”, which allows you to check the state with the ready
method, or use an onReady
callback to process your data when it arrives. (See http://docs.meteor.com/api/pubsub.html#Meteor-subscribe for more detail).
Or, you could write your own reactive context using Tracker.autorun
to eventually resolve the find
. (See http://docs.meteor.com/api/tracker.html#Tracker-autorun for more detail).
Just a final point for information - your subscription (as it stands) does not need to be in an autorun
. You should reserve that for when you want to reactively change the subscription.
2 Likes
Hi @robfallows
Nice response !
Thx a lot, really, I didnt know that onRendered and onCreated wasn’t reactive.
Tracker.autorun(function () {
});
Saved me… thx guy!
1 Like