Meteor template.rendered - Why is the collection empty?

Why is the return collection inside the rendered function empty in the following basic example?
Auto update enabled. After loading the call command page
Coll.find().fetch() inside javascript console returns the correct set of records

Here is the code

t.js

 Coll = new Meteor.Collection("coll"); if (Meteor.isClient) { Template.tpl.rendered = function(){ console.log(Coll.find().fetch()); // <-- This line prints empty array }; } if (Meteor.isServer) { Meteor.startup(function () { if (Coll.find().count() === 0) { var f = ["foo","bar"]; for (var i = 0; i < f.length; i++) Coll.insert({f: f[i]}); } }); } 

And t.html file

 <head> <title>test</title> </head> <body> {{> tpl}} </body> <template name="tpl"> Test tpl </template> 
+6
source share
1 answer

A meteor is built from a conductor type data structure. This means that the application first loads the HTML, and JS is sent first, and then later.

You must use reactivity to check for data changes or to verify that the subscription to the collection is complete (which entails the removal of the automatic publishing package). (You can check how to transfer the application to manual subscription in the documents: http://docs.meteor.com/#publishandsubscribe )

The subscription callback tells you when data is being returned:

 Meteor.subscribe("coll", function() { //Data subscription complete. All data is downloaded }); 

A template can also be made reactive (for example, the way you do it), but .rendered not called because Meteor first checks to see if the html template has changed, and only if it is different will it change its HTML and call the displayed callback.

What you have as an option here: 1) instead of Deps.autorun or

2) I'm not sure why you use this in your callback, but if you need to put it there, you need to make sure that the HTML template changes by entering something into the html from your collection, changes it when you enter new data.

+5
source

Source: https://habr.com/ru/post/944023/


All Articles