Refreshing client doesn't work after Meteor collection update

I am working with a collection that contains style properties that I loop through and apply to the corresponding element:

// server side
Meteor.publish('elements', function(){
  return Elements.find();
});

//client side
Meteor.subscribe("elements");

setupElements = function () {
    var currentUserId = Meteor.userId();
    var elements = Elements.find({user: currentUserId}).fetch();
    elements.forEach(function(e){
    var elementId = e._id;
    eval("document.getElementById('" + elementId + "').removeAttribute(\"style\")");
    var width = e.width;
      for (var i in width) {
        eval("document.getElementById('" + elementId + "').style.width"= \"" + width[i] + "\"");
      }
    });
}

Template.element.rendered = function() {
  if(!this._rendered) {
    this._rendered = true;

    // loop through elements and apply width style to each
    setupElements();
  }
}

// template
<template name="element">
  {{#each element}}
    <div id="{{_id}}" class="element">{{text}}</div>
  {{/each}}
  <button id="change-style">Change style</button>
</template>

Despite rendering the template and applying the appropriate widths to each element, when I trigger an update like so:

'click #change-style': function() {
    Meteor.call('updateElements'); // assuming the server-side method successfully updates all elements
    setupElements(); // expected this to fetch new styles and re-apply them
  },

The database gets updated on the server, but the changes are not reflected on the client-side template until I refresh the page or trigger the event again. It seems like the client-side does not automatically update when new data is received from the server. I am curious about the correct setup to make the style re-application reactive, or if there is a way to force the template to refresh.

Thank you in advance!

Answer №1

Although there are likely more efficient methods to accomplish your task using traditional reactive html & JQuery, for this specific scenario:

Remember that Javascript operates asynchronously. The setupElements function will execute before receiving the server responses. To address this, you can simply call it within the .call callback like so:

Meteor.call('updateElements', setupElements);

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

Learning to implement skip and take functions in JavaScript for a JSON array can greatly enhance the functionality and

I was wondering if it is possible to achieve the following functionality in JavaScript: for (let i = 0; i <= pieces; i++) { let piecesProducts = productList.slice(i * 2, i * 2 + 2); } I have a JSON array and I am looking to ext ...

State of an array has been modified

After toggling the state of a checkbox from true to false, calling setState does not immediately reflect the update on the screen. Instead, another element with state must be interacted with in order to trigger a refresh and display the new value of the ch ...

I am having trouble retrieving the information stored in an Array of Objects. Specifically, I am having difficulty accessing and iterating through each object using a for

Is there a way to extract data from an API individually and retrieve data from an Array? let {Array}=jsonData fetch("https://apis.ccbp.in/city-bikes?bike_name" + search, options) .then(function(response){ return response.json(); }) .then(funct ...

Updating a connected model in Sequelize using another model

Seeking guidance on updating a model with new associations in Sequelize. The model involves a many-to-many relationship with a join table. Attempted this code snippet: app.patch('/api/team/:id/newplayers', function(request, response){ const pl ...

Nuxt VueJS has various modules with names that have only minor differences in letter casing

I encountered an error while compiling with nuxtJS and couldn't find a solution on Google. The error seems to be related to declaring capital letters, but it is actually happening in the node_modules directory rather than in my components. [HMR] bund ...

How to toggle visibility of a div using Jquery

As a newcomer to Jquery and Javascript, I've been working on a project that I believe could be achieved more efficiently. Here is an excerpt of what I'm currently doing: HTML <a class="link1" href="#">Link 1</a> <a class="link2" ...

What is the best way to load a partial in Rails asynchronously with AJAX?

I am currently using the following code to load a partial when I reach the bottom of a div containing a table: $(document).ready(function () { $("#pastGigs").scroll(function () { if (isScrollBottom()) { $('#pastGig ...

Changing the structure of an array of objects

Currently, I am dealing with an API that provides an array of objects structured like this: [{match_id: "255232", country_id: "41", country_name: "England", league_id: "152", league_name: "National League", match_date: "2020-01-01", match_status: "", matc ...

Personalize the jquery autocomplete outcome

I'm currently utilizing jQuery autocomplete along with a remote data source. $( "input#searchbar" ).autocomplete({ source: function( request, response ) { $.ajax({type: "post", mode: "abort", dataType: ...

Passing Multiple GET Parameters in PHP Using Ajax

Currently, I am utilizing a set of buttons to filter a table of data in my project. Two buttons are functioning well with the code snippet below: <button onclick="filter('open');" class="open">Open</button> <button onclick="filte ...

What methods can I use to conceal elements of my object that do not align with my specified filter?

Currently, I have implemented a filter that searches for an object in a text field using the properties of title and name. If there are matches, the words are highlighted in yellow. I am interested in modifying this so that if there are matches, the other ...

What is the best MySQL data type for storing JavaScript code with PHP?

I am creating a platform that resembles jsfiddle, allowing users to store their JavaScript codes and retrieve them in an organized manner. I am unsure about which data type would be most suitable for saving the codes, or if storing them in text files wou ...

What is the best way to create a feature in Vue that filters options in real-time as we type into a

In my Vue application, I am trying to implement dynamic filtering for the options in a search box as the user types. Currently, the search box displays the entire list of options without any filtering happening even when the user is typing. <el-form-it ...

Integrate a @Component from Angular 2 into the Document Object Model of another component

One of my components is called TestPage import { Component } from '@angular/core'; @Component({ selector: 'test-component', template: '<b>Content</b>', }) export class TestPage { constructor() {} } Another ...

Creating an interactive accordion table using vue.js and the v-for directive in the main element

Looking for some help on implementing this feature using VUE: https://jsfiddle.net/jacekpr/roschwvL/5/ Currently, my progress is here: https://jsfiddle.net/jacekpr/8bhpqc5s/13/ However, I'm facing an issue with having multiple root elements in the ...

What is the best way to eliminate the external pause button?

My website contains the following HTML snippet: <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="a ...

Generating custom reports based on specific data fields

My current approach involves displaying all the columns for the searched records in a div with the id of searchresults using AJAX. I then provide a print option to print those records. However, I now want to enhance this functionality by allowing users to ...

Using a form generated on the fly for submission

Recently, I created a dynamic form that consists of select options and input boxes. Upon submitting the form, I require all data from the selects and inputs to be stored in separate variables. The following is an excerpt from the code: HTML CODE : < ...

The Cal.com vanilla javascript integration does not function properly when used with Svelte

I have been trying to integrate cal.com into a SvelteKit website, but I am facing difficulties implementing it using vanilla JavaScript as per the official documentation. While following the instructions provided for vanilla JavaScript, I had success with ...

Incorporating date formatting to the existing documents

The mongoose schema I have created is structured in the following way. mongoose.Schema({ "url": String, "translations": [ { "targetLang": String, "source": String, ...