I keep encountering a common error whenever a reactive variable is updated:
Exception in template helper: Error: $in needs an array
at Error (native)
at Object.ELEMENT_OPERATORS.$in.compileElementSelector (http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1827:15)
at http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1509:19
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?46eaedbdeb6e71c82af1b16f51c7da4127d6f285:157:22)
at operatorBranchedMatcher (http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1489:5)
at compileValueSelector (http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1393:12)
at http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1372:9
at Function._.each._.forEach (http://localhost:3000/packages/underscore.js?46eaedbdeb6e71c82af1b16f51c7da4127d6f285:157:22)
at compileDocumentSelector (http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1355:5)
at _.extend._compileSelector (http://localhost:3000/packages/minimongo.js?cdf1a26cf7719fa9471a8017c3defd5aea812727:1332:12)
The issue seems to be related to w
(reactive variable)
Here is the code snippet causing the error:
Template.cList.onCreated(function(){
var self = this;
self.d = new ReactiveVar()
self.w = new ReactiveVar()
self.autorun(function() {
var b = A.findOne(Pi());
if (b && b.array) {
var h = Subs.subscribe('B', b.array)
self.d.set(h.ready()) // is subscription ready?
self.w.set(b.array)
}
});
});
Template.cList.helpers({
cLists: function () {
if (Template.instance().d.get() && Template.instance().w.get()) { // run only when d and w is ready
return B.find({_id: {$in:Template.instance().w.get()}}, {fields: {title:1, src:1}});
}
}
});
Lets analyze step by step...
- No error on initial load
- Upon changing pages, the following dependency changes:
Pi()
- Autorun will trigger again.
- Due to change in
Pi()
, variables like
will also change.b && b.array && h && self.d.set(h.ready()) && self.w.set(b.array)
- I suspect that
cList
is computed immediately after page change without waiting for autorun re-computation to finish, resulting in the error being thrown. - After autorun completes the re-calculation of dependency changes,
cLists
displays the correct list based on the updated dependencies. There are no issues with the user interface, but the warning message is undesirable.
To prevent the warning mentioned above, I need to wait for cList
when dependencies change. How can I achieve this? How do I ensure the meteor helper waits for the re-calculation triggered by dependency changes in the template's autorun?