Trouble arises when attempting to execute a Vue method through a Vue computed property

It seems that the issue at hand is more related to general JavaScript rather than being specific to VueJS. I have a Vue Method set up to make a Firebase Call and return the requested object, which is functioning properly:

methods: {
  getSponsor (key) {
    db.ref('businesses').child(key).on('value', snap => {
      console.log(snap.val())
      return snap.val()
    })
  }
}

[Object]

However, when I invoke this method from a computed property, it returns as undefined:

computed: {
  sponsor () {
    console.log(this.getSponsor(key))
    return(this.getSponsor(key))
  }
}

Undefined

I'm curious as to why this is happening. Could it be related to how the method is being returned?

Answer №1

When a call is made to an async action, you exit the function context, which means that you cannot return a value from the callback function that will be returned in the main function.

To solve this issue, you can set a property in the data object from the callback function (make sure to declare it first), and then access the value of that property in your computed property.

 computed: {
    sponsor () {
        return(this.sponsor)
    }
}
methods: {
    getSponsor (key) {
        let self = this;
        db.ref('businesses').child(key).on('value', snap => {
            console.log(snap.val())
            self.sponsor =  snap.val()
        })
    }
}

If you call the getSponsor method inside your computed property, it will run twice - once during initialization and once when the sponsor property changes.

Since you only need it to run once, you can do so in beforeCreate, mounted, or any other lifecycle hook depending on your requirements.

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

Node, Express, and Angular redirection problem encountered

I have a web application built with node, express, and angular. The app consists of two main pages - a user profile page and a login page. My goal is to redirect any user who is not logged in to the login page when they try to access the profile page. Howe ...

Setting up a retrieval callback in mongoose and storing it in a global variable

Is there a way to set the value of db as a global variable? I am having trouble with getting the console output of name outside of the findOne function, it keeps showing me undefined. Any suggestions on how to fix this issue? var name; schema.findone({na ...

The issue of empty data in Symfony 3 Form Ajax Post Requests

Displaying a list of tags with the option to add more dynamically. Using Ajax instead of Symfony Doctrine for form submission to allow dynamic updates without page reloads. This is how the form is structured in HTML: <div class="tag-form" ...

What causes setInterval to create an endless loop when used inside a while loop in JavaScript?

I attempted to initiate a delayed "one" call or a "one or two?" question, but instead of working as expected, the function continued running indefinitely. Surprisingly, everything worked perfectly fine without using setInterval. quester2() function quest ...

Having trouble getting an HTML form to work when making a PHP and Ajax request

I am trying to validate an HTML form using Ajax to prevent the browser from loading the page. Ideally, when a user enters their first name, it should display above the HTML form. However, I am encountering an issue where it is not showing up as expected... ...

Using JavaScript's document.write method to display HTML code, along with a variable retrieved from a Flash application

Can I ask two questions at once? Firstly, how can I achieve the following? document.write(' <div id="jwplayer"> <center> <div id='mediaplayer'></div> <script type="text/javascript"> jwplayer('mediapl ...

Using VueJS to showcase user input in a dynamic list and a pop-up modal

I am attempting to achieve the following: Use a v-for loop to display form input (name, position, company) as an unordered list, showing only the name input and a button for each person When a button is clicked, a modal will appear displaying all the data ...

Deselect a checkbox by selecting a radio button with just Javascript code

Hey there! I'm currently delving into the world of pure JavaScript and could really use some guidance on a particular issue. Here's what I'm aiming to accomplish: I'd like to design a checkbox that triggers the opening of a window whe ...

Activate a JavaScript mouse event outside of an element

https://jsfiddle.net/f8L300ug/3/ Attempting to create a drag-to-resize feature, inspired by the provided example. One challenge encountered is that when the mouse is released outside of the <body>, the mouseup event does not trigger as expected. Th ...

Experiencing difficulties managing NodeJS session

I've been attempting to integrate a login feature into my nodejs-based web application. const express = require('express'); const app = express(); const route = express.router; const sessions = require("client-sessions"); app.use(sessions ...

A method for retrieving the variables from the initial API function for use in a subsequent API function

$.getJSON(url, function (data) { $.getJSON(url_wind, function (data2) { //perform actions with 'data' and 'data2' }); }); While attempting to use the data from the initial getJSON() call in the second getJSON() call ...

Using vuex-class to interact with Vuex in non-Vue components

Is it possible to access Vuex outside of a Vue component using vuex-class? In a typical scenario, the process is quite straightforward: // some JS file import store from './../store'; // path to Vuex store store.commit('ux/mutationName&ap ...

Enhance Your Browsing Experience with Ajax Chrome Extension

I tried sending the URL to a PHP file in a Chrome extension, but I'm having trouble getting a response. manifest.json { "name": "Get pages source", "version": "1.0", "manifest_version": 2, "description": "Get pages source from a popup", "b ...

Remove inline CSS from HTML elements

Having a large HTML file structured like this: <div style="min-height: 32px; padding: 5px; width: 800px; margin: 50px auto; overflow: auto; font-size: 12px;" class="selectable clearfix selected_layer" id="wrap"> <div class="selectable" id="l1" st ...

Error message in VueJS TypeScript: Implicit declaration of type 'props' as 'any'

Currently, I am working with vue 2.6 and typescript 3.8.3. The issue arises when I attempt to apply a validator to a prop. I am encountering error message TS7006: Parameter 'props' implicitly has an 'any' type. Below is the ...

The compatibility issue between Angular JS App and JSPDF is causing malfunctions specifically in Internet Explorer

I am currently working on an Angular JS application that utilizes JSPDF for generating PDFs. While the PDF generation functionality works perfectly fine on Chrome, Firefox, and Safari, it encounters issues on Internet Explorer (IE). The specific error mes ...

The click function is a member of an object within an emit event

I stumbled upon the code snippet below, which triggers the notification-alert event and passes an object as a parameter. this.$root.$emit('notification-alert', { text, type: 'warning', click: () = ...

Assistance with utilizing Regular Expressions to extract the className from a React/JSX component

For instance, I have <img className='class' src='somelink' /> and my goal is to extract only the className='class'. I have already attempted using / className='.+'[ |>] while going through files in search of ...

Tips on incorporating multiple lines of placeholder text into a textarea field:

Is it possible to add multi-line placeholder text in a textarea? I found this solution, but unfortunately it does not work on Mozilla and Safari. It seems Chrome is the only browser where this method works: $('#nameTxtBox').attr("placeholder", ...

Steps for repairing a damaged vuejs project following the inclusion of the "less" and "less-loader" modules

I recently set up a basic vuejs project in IntelliJ and decided to integrate Less into it. However, when I executed "npm install -D less less-loader," an error occurred that I can't seem to resolve. I attempted to downgrade webpack and less-loader wit ...