Receive real-time updates from the query and then provide the results using Vuex and Firestore

I have encountered an issue while trying to retrieve data from a Firestore real-time query and perform other actions. Although I am able to receive the data from Firebase as an Object, I am facing a problem when trying to access the properties of the returned Object as they appear to be empty.

Vuex Action

export const getThreadMembers = async ({ commit,dispatch }, payload) => {
      try {
        let members = {}
        const threadMembersRef = await db.collection('members')
                                  .doc(payload.threadId)

        threadMembersRef.onSnapshot(function(doc) {
          Object.assign(members,doc.data())
        })   
        
        return Promise.resolve(members)
      } catch (error) {
        return  Promise.reject(error)
      }
    }

/*
 * this is a function for test purpose only
 */ 
export const delay = ({commit}) => {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve(42); // After 3 seconds, resolve the promise with value 42
    }, 3000);
  });
}

Component file

      created () {
        this.getThreadMembers({
          threadId: this.threadId
        }).then(members => {
          console.log(members)
          console.log(Object.getOwnPropertyNames(members))

        })
      }

Question:

Why is

Object.getOwnPropertyNames(members)
executed before members?

Answer №1

The process carried out by onSnapshot occurs asynchronously, but the current setup does not include handling it, leading to the continuation of the function without waiting for the promise to be fulfilled. Utilizing await provides a solution to this issue.

const doc = await threadMembersRef.onSnapshot()
Object.assign(members, doc.data())

Additionally, there is no necessity to use await on threadMembersRef since it only involves assigning a reference, not executing any actions.

const threadMembersRef = db.collection('members')
                          .doc(payload.threadId)

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

Adapting to more user inputs in accordance with the feedback received from the AJAX response

Two user inputs are being received: area time Utilizing this information, the available restaurants in the specified area during that particular time are displayed. In addition, all the cuisines offered by these restaurants are displayed as checkboxes. ...

How to Build a Bootstrap Table using PHP and JSON Data?

Trying to use json data like this https://i.sstatic.net/iRUUE.png {"endpoint":"127.0.0.1","id":1,"identifiers":["license:LICENSEKEY","xbl:XBLKEY","live:LIVEKEY","discord:DISCORDID&q ...

Is there a way to change an element's display to 'block'? (see more information below)

I'm having an issue with my event listener for a button that is supposed to change the css of #popUpForm. It seems to only work when I add inline css directly to #popUpForm. Is there a way to achieve this without using inline css and instead setting t ...

Having trouble with Vue's $route.push method not working when invoked from a method?

I am currently in the process of creating a search bar for my application using the vue-bootstrap-typeahead autocomplete library. For those unfamiliar, when an option is selected from the suggestions list, it triggers the @hit event which passes the result ...

Ways to assign a secondary color theme to the DatePicker widget

As someone who is new to exploring Material UI components, I encountered a roadblock while experimenting with different features. <TextField type="email" name="email" id="email" label="Email" variant="outlined" color="secondary" required /> <D ...

The process of assigning a function to an object in JavaScript is currently not functioning properly

After updating a Vue2 project to Vue3, I ran into an issue with Javascript. It seems that the language now prevents me from assigning a function to an object. In the code below, I define a function "bar" within a loop. While I can successfully call the fu ...

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

Integrate a PHP link into a Gatsby/React project

I've been attempting to connect my contact form page, contactpage.php, with my Gatsby application. In the navigation bar (found in the Components folder), I've added the following code: <div> <a className="int_link_about" ...

Utilizing headless Chrome to automatically capture AJAX requests

Chrome officially supports running the browser in headless mode, allowing for programmatic control through the Puppeteer API and/or the CRI library. I've thoroughly explored the documentation but have not discovered a method to programmatically captu ...

Is there a Possible Bug with Highcharts Categories?

I am in the process of creating a dynamic sales dashboard that automatically updates a column chart displaying the latest sales figures for a team of agents. Within this project, I have developed a function called updateChart() which carries out the follo ...

Is there a way to use an Angular expression inside an HTML document to determine if a variable is a boolean type?

I'm working with an element in my HTML where I need to determine the type of a variable, specifically whether it's a boolean or not. <button process-indicator="{{typeof(button.processIndicator) === 'boolean' ? 'modalProcess&apo ...

Discovering the Value of TD when Clicked in MVC

I have been struggling to extract a value or string from a td in a table, but none of the clickevents I've used seem to work. Here is the structure of the table: <table id="tblMain"> <thead> <tr> ... </tr> ...

Trigger ExtJS input file event when dialogue window is closed

How can we capture the event when a file is selected in an open dialogue box and the OK button is clicked in extjs? **Off topic, the field does not stretch from its normal width. xtype: 'textfield', fieldLabel: 'New (JPG or ...

Restricting the length of dynamic dropdowns in a React application

Click here to view the code on CodeSandbox My dropdown menu options are dynamically generated and filtered based on custom data. const dropdownData = [ { code: "others", name: "Others", amenity: [] }, { code: "bed", name: "Bed", ...

There was an error in Threejs' PropertyBinding as it attempted to parse the trackName ".bones[].position

Version: THREE.WebGLRenderer 91dev Struggling to achieve a basic chest opening animation using three.js. Unfortunately, encountering an error while trying to create an action. PropertyBinding: Unable to interpret trackName: .bones[].position Link to t ...

Objects within the Prototype in Javascript

While delving into the world of AngularJS, I stumbled upon an interesting revelation - when objects are placed in a prototype object, any instances inheriting from that prototype will alter the prototype's objects upon assignment. For example: funct ...

Using ng-non-bindable along with ng-if in Angular Google Maps allows for certain elements or

I recently came across an interesting discussion on the necessity of ng-non-bindable for the <ui-gmap-windows> element in Angular Google Maps. It shed some light on how ng-non-bindable is utilized in the directive. However, I encountered an issue wh ...

Sending multiple objects using Ajax and fetching them in PHP

I'm facing an issue with posting a form and an array to my PHP script. My current approach involves using the following code: var json_data = JSON.stringify(data_vendor); //array to be posted $.ajax({ url: &ap ...

Tutorial on displaying historical pricing data on a chart utilizing props in Vue Chartkick

I recently discovered a chart library called Chartkick for Vue projects. If you're interested, you can check it out here: In my project, I have data passed as props to a component. However, I encountered an issue where the prop couldn't be acces ...

What is the best way to interrupt the current song playing?

I am currently working on developing an audio player using reactjs that has a design similar to this https://i.sstatic.net/Hnw0C.png. The song boxes are rendered within a map function, and when any song box is clicked, it should start playing. However, I a ...