Constantly loading image with Meteor HTTP request

Within my Meteor application, I am attempting to dynamically load a random image from an API which returns JSON data structured like this:

{
 "id":2026
 "url": "https:// ... " ,
 "large_url":null,
 "source_id":609,
 "copyright":"CC0",
 "site":"unsplash"
}

My current approach looks like the following:

if (Meteor.isClient) {
    Template.body.helpers({
        randomImage: function() {
            Meteor.call("unImage", function(error, results) {
                Session.set('url', results.data.url);
            });
            return Session.get('url');
       }
    });
}

if (Meteor.isServer) {
    Meteor.methods({
        unImage: function() {
            this.unblock();
            return Meteor.http.call("GET", "http://www.splashbase.co/api/v1/images/random");
        }
    });
}

In my HTML structure:

<div class="header" style="background-image: url('{{randomImage}}')">
  ...
</div>

Although this method is functional, it ends up refreshing the image approximately every second. This behavior leads me to believe that the unImage function on the server side is constantly reloading due to some underlying process or configuration. Any suggestions on resolving this issue and understanding why it persists?

Answer №1

The reason behind this behavior is the session variable being used inside your randomImage helper function. When it comes to Session variables, they are reactive in nature, meaning they re-run whenever their value changes.

In this scenario, the helper code keeps re-running continuously, causing Meteor methods to be called repeatedly.

To address this issue, you should move the Meteor.call function from the helper to the rendered event as illustrated below:

if (Meteor.isClient) {
    Template.body.rendered= function(){
       Meteor.call("unImage", function(error, results) {
          Session.set('url', results.data.url);
       });
    }

    Template.body.helpers({
        randomImage: function() {
            return Session.get('url');
       }
    });
}

This adjustment ensures that the Meteor method is only called once the template is fully loaded, setting the url variable and allowing the randomImage helper to reactively retrieve its value.

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

The parameter "file" needs to be a string data type, but npm run deploy to gh-pages received an undefined data type instead

I encountered an error while attempting to deploy a react application to gh-pages. Despite having successfully done it in the past, this is the first time I am facing this specific issue. The error message reads: The "file" argument must be of type string ...

Retrieving information from MongoDB queries using Node.js

I am facing an issue while trying to retrieve data from the find() method and use it outside the method. My goal is to incorporate this data into a JSON response. Unfortunately, my current code is not working as expected and the data is not accessible outs ...

Converting JSONObject into a Document

Hello, I am new to using MongoDB and I am trying to figure out how to convert a JSONObject to a Document and then store it in MongoDB. Here is the code snippet that I have so far - I receive a service API response in JSON format. CloseableHttpResponse res ...

Storing the created .wav file on the server using PHP

Is there another way to handle this? How can I manage streaming of a WAV file? I'm currently working on a platform that allows users to create their music compositions and the system outputs a .wav file for each creation. While I can play the mus ...

Tips for avoiding backslashes when creating a JSON file using PySpark

I am trying to format data into a JSON file using PySpark. Here is the desired format: { "list-item": [ {"author":"author1","title":"title1","pages":1,"email":"<a href="/cd ...

The webpage is unreachable on localhost after attempting to write to a file using node.js

I'm currently attempting to update a file using Node.js. I have a form that contains checkboxes, and upon form submission, the server should update the file based on which checkboxes are selected: a, b, or c. The JSON file structure is as follows: { ...

Retrieve a single document from Firestore and assign it to a variable

While I'm still new to NodeJS, I'm currently working on retrieving a single User document from Firestore. const fs = firebase.firestore(); const usersRef = fs.collection('users'); let findUserByContact = (contact) => { let res ...

Building a Slider component in a React class using Materialize CSS

I currently have a functioning slider implemented in a React function component. I am now looking to correctly integrate the slider below into a React class component. import * as React from 'react'; import Box from '@mui/material/Box'; ...

Attempting to crack the code within body-parser and Node.js

I am just getting started with Node.js & Express and trying to follow a tutorial at https://github.com/jw84/messenger-bot-tutorial. I have a good understanding of most parts, but I'm confused about the use of "entry" and "messaging" in this code snipp ...

Combining AngularJS with ng file upload and Sails JS for seamless file uploading

When I upload a file, I also need to send some additional information along with it. The instructions mention using the data parameter for this purpose, but I'm having trouble accessing it in my Sails controller action. Frontend: Upload.upload({ url ...

A guide on smoothly navigating to the desired row in a gridview using Asp.net

Currently, I am developing a project using ASP.net and C# technology. In my application, I integrated a GridView that contains multiple rows. Within the grid, there is a text box and a search button available. The columns displayed in the grid are Id and ...

Running AngularJS controllers should only occur once the initialization process has been fully completed

I am facing a situation where I need to load some essential global data before any controller is triggered in my AngularJS application. This essentially means resolving dependencies on a global level within AngularJS. As an example, let's consider a ...

Issue with the execution of Javascript code. Edit required

After creating a registration form that allows users to input their information for registration, I encountered an issue where if certain fields were left empty or if the user name was unavailable or the email address was already registered, a warning mess ...

Adding fresh information to a data entity

I'm currently in the process of updating a data object with a new value. Upon checking, if the data associated with event.data.id exists within $("#ArticlesHolder"), I proceed to update it as follows: if($("#ArticlesHolder").data(event.data.id) != n ...

I just stumbled upon Jupyter and I'm curious - can I utilize Javascript and store it in the cloud?

Yesterday evening, I stumbled upon Jupyter and began using it alongside Python. It seems like an excellent tool for coding, something that I've been in need of, but I'm not sure if I can integrate JavaScript with it. I noticed there are npm packa ...

Troubleshooting difficulties integrating NodeJS with R using an R script

I have been attempting to execute an R-script from a js-file but I am consistently receiving a null value as the return. Here is my folder structure: -R_test --example.js --helloWorld.R The contents of example.js are as follows: var R = require(" ...

How to save array data to a text file using node.js

I have an array containing values that I want to write to a text file using the following code. while(filedataarr.length>0) { firstelement = filedataarr.shift(); //console.log(firstelement); fs.appendFile("D:\\Temp& ...

Issues with utilizing $http POST

I am a beginner in angular.js and I want to create a form with 2 number fields. When I click on submit, I need to send the data to the server using JSON for calculating the sum. For example, if I input 4 in the first field and 4 in the second field, it sho ...

Tips for toggling the appearance of like and add to cart icons

I am attempting to create a simple functionality for liking and adding items to a cart by clicking on the icons, which should immediately change the icon's color when clicked. However, I am facing an issue where the parent div's link is also bein ...

Combine and update JSON files by matching ID's in PHP

I am facing an issue with merging JSON files in PHP. I want to overwrite data when the id's match, but it's not working as expected. Here is my PHP code: foreach($instagram_array['data'] as $key => $image){ $id = $image['id ...