What is the best method to delay the computation in meteor.helper until after a re-computation is triggered by a change in dependency within the template.autorun

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...

  1. No error on initial load
  2. Upon changing pages, the following dependency changes: Pi()
  3. Autorun will trigger again.
  4. Due to change in Pi(), variables like
    b && b.array && h && self.d.set(h.ready()) && self.w.set(b.array)
    will also change.
  5. I suspect that cList is computed immediately after page change without waiting for autorun re-computation to finish, resulting in the error being thrown.
  6. 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?

Answer №1

the root cause is the ready callback within the meteorhacks:subs-manager package... replacing it with template subscription will prevent the error...

Template.cList.onCreated(function(){
  var self = this;
  self.d = new ReactiveVar()
  self.w = new ReactiveVar()
  self.autorun(function() {
    var result = A.findOne(Pi());
    if (result && result.array) {
      self.subscribe('B', result.array)
      self.w.set(result.array)
    }
  });
});

Template.cList.helpers({
  cLists: function () {
    if (Template.instance().subscriptionsReady() && Template.instance().w.get()) {  // execute only when both subscription and w are ready
      return B.find({_id: {$in:Template.instance().w.get()}}, {fields: {title:1, src:1}});
    }
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Navigating through the directories in PUG using the absolute path

Referring to the docs for PUG (), it states: If a path is absolute (example: include /root.pug), it gets resolved by prepending options.basedir. Otherwise, paths are resolved in relation to the file being compiled. To clarify, I understand that this in ...

Tips for fetching form data transmitted via HTTPS in Node.js?

As someone new to back-end security, I'm hoping for some guidance without judgement: When receiving values over HTTP in my node application, the form data is easily accessible in the request object using req.body.{name of input element} However, whe ...

Guide to transferring information from the scenario file to the function file through regular expressions?

This project utilizes NodeJS, Cucumber, Gherkin, and Selenium. In an attempt to pass a stored value or a URL into the step definitions file using regular expressions, I am encountering some challenges. In my example feature file, I have tried utilizing &a ...

`` `Are you unsure when to use arrayobject instead of objectarray in JavaScript?

I'm struggling to understand when it's best to declare an object inside an array or an array inside an object. Object inside an array var users = [{'Name': 'Alex', 'Value': 2}] Array inside an object var user_dat ...

Issue with onClick function causing failure to generate options in select menu

function getOption(){ var select = document.getElementById("dynamic-select"); if(select.options.length > 0) { var option = select.options[select.selectedIndex]; alert("Text: " + option.text + "\nValue: " + option.value); ...

Is it possible to utilize a ternary operator in AngularJS beyond just the class attribute?

Struggling with handling null values while looping through a JSON object using AngularJS. I am still learning the ropes of Angular. <a href="#" data-mycustom="{{product.related}}">...</a> If the 'related' property is null: { " ...

Validating HTML and JavaScript syntax in the Ace editor

Currently, I am utilizing Ace Editor and facing the challenge of enabling live syntax checking for both HTML markup and JavaScript code within the editor. When I set "ace/mode/html" it only checks the HTML syntax. For example, in the following code snippe ...

Strip all null entries from the URL string

I'm attempting to eliminate all empty parameters from a URL string. This is how my URL appears: http://localhost/wm/frontend/www/?test=&lol=1&boo=2 The desired output from my code should be: http://localhost/wm/frontend/www/?lol=1&boo=2 ...

Tactile interactions on iPhone

My goal is to create an off-canvas menu that can be opened with touch events in a systematic way. It functions perfectly in my browser when I click and drag on the body to reveal the menu. However, it encounters a problem on the iPhone. The error message ...

Contentful integrated into a NuxtJs website

After successfully creating a blog using Nuxt JS and integrating Contentful into the project, I followed a helpful tutorial from here. This enabled me to retrieve all sections such as title, date, and content of the post efficiently. However, I am current ...

The use of an Authorization header is not compatible with HTTP GET requests

I recently incorporated VueSession into my project to handle user sessions. One of the components in my application is a login form that communicates with my backend (Django) to obtain a JWT token. However, I encountered an issue where although the login p ...

Outside of the for loop, a JavaScript object is accessible, but inside the loop, it is undefined

I have a question that I need help with. After parsing a JSON object from an AJAX request, I obtained an object called usrobj. console.log(usrobj.available[0]); The usrobj.available is actually an array: (2) [{…}, {…}] 0:{currency: "ETH", amount: "0 ...

JavaScript: Issues with Updating Global Variables

I am currently working on a web application that generates a map of the United States and colors it based on financial data from a specified range of years selected using a slider. The functionality involves drawing three maps and having three buttons to ...

Unable to create account using PHP

Every time I attempt to create an account, the data I receive is always problematic. The username must be between 3 and 15 characters I find it frustrating that the account creation never goes through successfully. What baffles me even more is that af ...

Vue alert: Issue in v-on function: 'TypeError: Unable to access property 'Array' of undefined

When I click on the button, I want to validate the inputs for empty values. I am attempting to filter the array and add an error to the array if any of the inputs are empty. However, upon clicking the button, I encounter the error message "'Error ...

The technique of accessing parent props from a child composition component in React

I am trying to reduce every letter prop from the child component, Palata. How can I achieve this? index.js <Block letter="I" mb={16}> <Palata letter="I" start={4} end={9}/> <Wall/> <Empty/> <Palata le ...

Make a hyperlink in Internet Explorer redirect to open in Mozilla Firefox

I am struggling with linking two URLs from a corporate intranet site built on Sharepoint to Firefox. The issue is that the links lead to an external site that doesn't function properly in Internet Explorer, which is the default browser for most users. ...

A guide on implementing nested view objects in ui-router for angular applications

Unfortunately, I am not well-versed in Angular. My objective is to display multiple views on a user profile page using ui-router. These are my current routes: (function() { 'use strict'; angular .module('app.routes') .config(r ...

Having trouble with AngularJS - struggling to diagnose the issue

HTML Page <head> <title>TODO supply a title</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <script src="assets/js/angular.min.js"></script> ...

Guide to incorporating rate-limiter-flexible into your current node.js express configuration

I am currently using node.js, passport, and JWT bearer token for securing my routes. However, I have yet to implement rate limiting and IP/user blocking for too many false login attempts. What is the recommended approach to integrate this into my existing ...