Generate a random number in VueJS only one time

I am experimenting with creating a VueJS application that can utilize multiple APIs to fetch and display images to the user. This is my first attempt at using Vue, so please be patient if I rely on vanilla JS instead of VueJS functions.

The desired functionality is for the user to click a button, triggering a request for an image from one of the APIs available. The twist is that I want the Flickr API to require a specific tag (chosen randomly from an array) each time it's called. However, currently, the tag remains the same every time the function is executed again without page reload.

Why is this happening and how can I resolve it? Your help is greatly appreciated.

Here is the code I have written so far:

var vm = new Vue({
    el: '#app',
    data() {
        return {
            // some data
            apis: [this.flickr(), this.desktopper()],
            wallpaper: '',
            wallpapers: [],
            screenWidth: window.screen.width,
            screenHeight: window.screen.height,
        }
    },
    methods: {
        // Random number generator
        randomNumber(min, max) {
            return Math.floor(Math.random() * (max - min) + min);
        },
        // Main function to call an API and get the image source
        requestWallpaper() {
            var wallpaper = this.apis[this.randomNumber(0, this.apis.length)];
            console.log(wallpaper);
        },
        // Fetch random image from Flickr API
        flickr() {
            var popularTags = ['sunset','beach','water','sky','red','flower','nature','blue','night','white','tree','green','flowers','portrait','art','light','snow','dog','sun','clouds','cat','park','winter','landscape','street','summer','sea','city','trees','yellow','lake','christmas','people','bridge','family','bird','river','pink','house','car','food', 'bw','old','macro','music','new','moon','orange','garden','blackandwhite'];
            var tag = popularTags[this.randomNumber(0, popularTags.length)];
            return tag;
        },
        // Fetch random image from Desktopper.co API
        desktopper() {
            return 'desktoppr';
        }
    }
});

HTML:

<body>
<div id="app">
    <div>
        <div>
            <img id="random" src="" />
        </div>
        <div>
            <button v-on:click="requestWallpaper">New Wallpaper</button>
        </div>
    </div>
</div>
</body>

Answer №1

The issue lies within your apis array.

apis: [this.instagram(), this.twitter()],

You are invoking both the instagram() and twitter() methods by using parentheses (). This means you are passing arguments to these methods. Instead, you should remove the parentheses to store only a reference to each method.

apis: [this.instagram, this.twitter],

So when you make a call to fetchFeed(), first retrieve a random API reference, and then execute it using that reference.

// obtain a random API reference
var api = this.apis[ this.randomNumber(0, this.apis.length) ];
// invoke the reference, include parentheses to get the feed result
var feedResult = api()

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

Is it possible to reverse search a JSON array using regular expressions?

My situation involves a JSON string structured like the example found here. This JSON string holds data pertaining to players and their presets, formatted as follows: { "players": { <playerID>: { "presets": [{ ...

Use angular, javascript, or FormIo to set the cookie value to a dropdown list within a form as it loads

Currently, I am utilizing the Formio form within my Angular application. The registration form in my app consists of various fields, including State and city dropdowns that load values from State and city Formio resources. Whenever a user clicks on the Reg ...

Can anyone suggest a way to iterate over an object and substitute spaces in the keys?

I need to iterate through a dynamically-created object that contains properties with values. The issue is that the property names in this dynamic object contain spaces, which are not allowed in JavaScript object properties. How can I loop through this ob ...

The error encountered with react createRef was caused by a faulty implementation

Here is the revised question post completing the answer In this particular code snippet, I have encountered an issue where my file browser opens correctly upon submission, however, the updated state is not reflected when I click the final submit button. ...

Steps to create an instance method that only accepts the name of another instance method

I am looking to enhance an object by adding a method that specifically accepts the name of another method within the object. How can I achieve this in a way that dynamically narrows down the accepted names of methods, without hardcoding them? Let's t ...

Passing information as a parameter from Wordpress to a page

I am working on a project that includes a Google Maps streetview feature. [streetview width="100%" height="250px" lat="34.360988" lng="-86.693436" heading="-94.17771883289124" pitch="-3.342175066312998" zoom="1"][/streetview] For my project, I need to sh ...

What sets apart the <script> tag with a type attribute from the standard <script> tag in HTML?

Similar Question: Is it necessary to include type=“text/javascript” in SCRIPT tags? While working on my HTML project, I noticed that the JavaScript code within script tags is evaluated even if the type attribute is not explicitly set to "j ...

Is there a way to send data to a sibling component without the need to store it as a variable?

In my project, I am utilizing bootstrap vue cards within a v-for loop. Within this loop, one of the tags is supposed to return a value based on the current iteration of v-for. My challenge is that when I save this value as a variable and pass it to another ...

Exploring the reactivity of Vue on object graphs that include cyclic references

First and foremost, let me provide some context: I am currently in the process of developing a minesweeper application using VueJS. The grid is structured as an object tree, where each Box object contains a 'neighbors' property that stores Box o ...

Tips for updating the css class for multiple DOM elements using jQuery

I am currently attempting to modify the class property of a specific DOM element (in this case, a label tag) using jQuery version 1.10.2. Here is the code snippet I have written: var MyNameSpace = MyNameSpace || {}; MyNameSpace.enableDisableLabels = (f ...

A declaration of "import '***.css';" was located within an ECMAScript module file in the monaco-editor npm library

It's perplexing to me why the developers of monaco-editor included these statements, as they are actually causing errors in my browser such as: Failed to load module script: Expected a JavaScript module script but the server responded with a MIME typ ...

Creating cartoons from images using JavaScript

Recently, I've been experimenting with comicify for a new project. I found that by right-clicking on an image online, copying it, and then pasting it into this demo page created by the author, everything works smoothly. However, I wanted to take it a ...

Retrieving column values from a Datatable is limited to the first 10 rows

Trying to extract the values from column 1. I followed the instructions provided in the datatable documentation: var data = table.column( 0 ).data(); Table setup: var datatable = table.dataTable({ "scrollX" : "100%", "scrollY" ...

Contrasting the purpose of a function in pure JavaScript versus a function within the scope of an Angular controller

Could someone clarify the distinction between declaring these two functions in an angular controller? function demo() { }; scope.demo = function() { }; Are these two functions similar in perf ...

Unable to inject dependencies into Karma testing framework

I am facing the challenge of injecting the $urlRouterProvider into my tests, but I persistently encounter the unknown provider issue. My setup involves ui.router and the testing of directives, requiring access to these providers to prevent test failures... ...

Discover how to utilize images encoded in base64 format within webhook embeds on Discord

Can someone help me with inserting an image into a Discord embed using a webhook? I have the image saved as a base64 string obtained from a database. However, my attempts so far have only resulted in an empty embed. https://i.sstatic.net/CVs4j.png const d ...

Switching elements in an array using Vue.js

Within my vue.js web application, I am attempting to switch the positions of two rows in a forum. Below is the code snippet I am using: export default { data() { return { forums: [] } }, met ...

How to Import Components that Have Imports in MDX-Bundler within Nextjs

Is it possible to use mdx-bundler to import a file that itself imports another file? Currently, in my .mdx file, I have the following code: import MyComponent from './MyComponent' This is my *mdx* file. <MyComponent /> This works fine a ...

Transferring information between React components

After sending a request to retrieve all matching data from the database based on the answers provided in a questionnaire, I intend to utilize the data in a separate component to showcase the outcomes. <div className='row justify-content-end mt-3 p ...

Is it possible to gather element attributes using jQuery and store them in an array

let itemWidths = []; $('#menu').children().each(function(){ let width = $(this).width(); itemWidths.push(width); }); console.log(itemWidths); This code snippet is not functioning as expected. How can I modify it to store element properties ...