Having difficulty generating a Meteor.js helper using a parse.com query

Utilizing my meteor application, I fetch and display data from Parse.com. Initially, I integrated the parse.com javascript query directly into the template's rendered function, which was successful.

Now, I aim to utilize the Parse.com query in a helper function to pass it to a meteor {{#each}} loop within my template.

Template.dashboard.helpers({
app: function () {
    //initialize new array
    var appsArr = [];
    //Create a Parse Query for Post objects
    var query = new Parse.Query("Apps");
    query.descending("createdAt");
    var appsObj = {};
    query.find({
        success: function(results) {
            // Add the returned Parse.Object values to appsArr
            for (var i = 0; i < results.length; i++) {
                appsObj = {};
                appsObj.obid = results[i].id;
                appsObj.title = results[i].attributes.title;
                appsObj.screenshot1 = results[i].attributes.screenshot1._url;
                appsObj.appIcon = results[i].attributes.appIcon._url;
                appsArr.push(appsObj);
            }
        },
        error: function(error) {
            alert("Error: " + error.code + " " + error.message);
        }
    });

    return appsArr
}
});

Whenever I attempt to return my array (appsArr) in the helper function, I encounter the error: "Exception in template helper: undefined". Furthermore, I am unable to view my parse objects in the console. Nonetheless, the same code functions correctly in the rendered function.

Being relatively new to Meteor.js and Blaze templates, I seek assistance in properly implementing this parse query within the helper function so that I can use {{#each}} in the template.

 {{#each app}}
        <h3 class="app-title">{{title}}</h3>
{{/each}} 

Your help is greatly appreciated!

Answer №1

Due to the asynchronous and non-blocking nature of the query.find function, you cannot simply assign variables in the callback and return them outside the callback. This is because the callback may not have run by the time you reach the return statement, resulting in returning undefined data.

An effective method to work around this issue is to use a reactive variable (a variable with watched assignment). You can opt for either the [ReactiveVar][1] or the built-in reactive [Session][2] variable. In my practice, I prefer using the Session. An example implementation could look something like this (please note that this snippet has not been tested beforehand):

Template.dashboard.onRendered({ // onRendered, calculate appVar
  Session.set('appsVar', null); // reset appsVar immediately -- you can also do this in onCreated / onDestroyed to clean up
  // initialize new array
  var appsArr = [];
  // Create a Parse Query for Post objects
  var query = new Parse.Query("Apps");
  query.descending("createdAt");
  var appsObj = {};
  query.find({
    success: function(results) {
        // Add the returned Parse.Object values to appsArr
        for (var i = 0; i < results.length; i++) {
            appsObj = {};
            appsObj.obid = results[i].id;
            appsObj.title = results[i].attributes.title;
            appsObj.screenshot1 = results[i].attributes.screenshot1._url;
            appsObj.appIcon = results[i].attributes.appIcon._url;
            appsArr.push(appsObj);
        }

        Session.set('appsVar', appsVar);
      },
      error: function(error) {
          alert("Error: " + error.code + " " + error.message);
      }
    });
  }
});

Template.dashboard.helpers({
  app: function() { return Session.get('appsVar'); } // This will re-run when Session.appsVar is updated in the above callback.
});

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

Accessing index.html via file:// from Vue-cli template

Whenever I execute the npm run build command using this Vue-cli template, it displays this message: Hint: The built files are designed to be served over an HTTP server. Attempting to open index.html via file:// will not function correctly. Therefore, the ...

Positioning a Material UI Menu item underneath its parent element using CSS styling

I have created a Material UI dialog that features some text and an Icon with a dropdown menu option. You can check out the demo here: https://codesandbox.io/s/prod-rain-1rwhf?file=/src/App.js My goal is to properly position the Menu component so that it a ...

Top method for changing an array in javascript

I'm in the process of building a react application, and I've received the following array from an API call. var arrayLike ={ "2020-W1": [ { "type": "TAX_REFUND_IN_INT", &q ...

Oops! The system encountered a problem while trying to identify the value `Han` for the property `Script

I'm attempting to extract Chinese characters from a string. According to this particular answer, the following code snippet should work: const nonChinese = /[^\p{Script=Han}]/gimu; const text = "asdP asfasf这些年asfagg 我开源的 几 ...

Calculating a Price Quote

I have created a dynamic quote calculator for a Next.js project that allows users to calculate prices based on word count and selected languages. Currently, the price is calculated using a fixed rate of 0.05 per word. 'use client'; import { useS ...

Using JSON data to render images onto a canvas

I am encountering an issue with a JSON array that I'm receiving from PHP. The array is indexed and has the following format (larger in real scenario) [ [ [17, 28, 1, "z"], [28, 31, 6, "b"], [8, 29, 6, "b"] ...

Unlock the Power of jQuery Plugins: Implementing Global Settings Modifications

I have developed a jQuery plugin ( https://github.com/OscarGodson/jKey ) and some users are requesting localization support. My initial idea was to add an additional parameter in the plugin for localization, such as: $(window).jkey('?',callback, ...

Utilizing the Django object array in AngularJS – a comprehensive guide

I have a Django variable structured like this: [<Topic object>, <Topic object>] When passing it to Angular using ng-init, I wrote the following: <div class="profile-navigation" ng-init="ProfileTopics={{ProfileTopics|safe}} "> However, ...

Encountering the "excessive re-renders" issue when transferring data through React Context

React Context i18n Implementation i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: { en: { translation: translationsEn }, bn: { translation: translationsBn }, }, lng: "bn ...

Can you explain the concept of "Import trace for requested module" and provide instructions on how to resolve any issues that

Hello everyone, I am new to this site so please forgive me if my question is not perfect. My app was working fine without any issues until today when I tried to run npm run dev. I didn't make any changes, just ran the command and received a strange er ...

Creating interactive PDF files using ReactJS

Is there a way to create a PDF using React that supports styling and allows the content to be hidden on the page? I need to have a link in my app that, when clicked, generates a PDF and opens it in a new tab. I've tried out various packages but none s ...

What is the default way to toggle content in rows using Material UI?

Currently, I am utilizing Muitables and have a query regarding how to set the expanded rows to be displayed by default, similar to the illustration below: Upon initial page load, it is preferred for the content in that row to automatically expand (arrow d ...

Is there a way to retrieve the file path of the file that is imported using an alias in Vite (Vue3)?

Hello! I have a few inquiries. Is it feasible to obtain the file path of the file utilizing an alias for import in Vite (Vue3)? Setup Here's the directory structure I'm using, purely for illustrative purposes: src/ module_a/ some_ ...

How can the click event for a SubMenu in Ant Design be deactivated?

Is there a way to keep the SubMenu from toggling its child menus when clicked, without disabling it? I would like the SubMenu to maintain its appearance while preventing its children from expanding or collapsing. ...

What sets usePreloadedQuery apart from useQueryLoader?

I've been exploring graphQL and the react-relay library. These are the key points I've covered: Rendering Queries: where usePreloadedQuery is introduced. Fetching Queries for Render: where useQueryLoader is introduced. To keep it simple, I&apo ...

Could there be an issue with my function parameters, or is there another underlying problem?

Hey there! I've been working on this function, but it doesn't seem to be running quite right. Here's the code: function chooseCols(colTag, tagName) { // Set column name var column = $('.tagChooser:eq(&apo ...

If you want to retrieve the calculated value of a div using jQuery

I have a scenario where I have 3 list items (li) under an unordered list (ul). I am interested in finding the height of these list items, but without explicitly defining their height. So far, when inspecting with Firebug, I noticed that the computed height ...

Tips on connecting data within a jQuery element to a table of data

I am currently developing a program that involves searching the source code to list out element names and their corresponding IDs. Instead of displaying this information in alert popups, I would like to present it neatly within a data table. <script> ...

Exploring Ways to Retrieve Depth Information within three.js

I have come across shaders that can dynamically create outlines around edges based on the difference in depth of pixels. This means that pixels with less depth compared to their adjacent pixels might have a thinner outline or none at all. Examples of such ...

Using Unicode JSON in Laravel blade to pass data to React components, encountering an issue with JSON parsing

I currently have a JSON object stored in the database: { "ui": {}, "title": "Hola mundo 2", "values": {}, "properties": {}, "description": "descripcion" } Within the Laravel controller, ...