Adding Firestore document IDs to an array

I am exploring Vue.js and Firestore for the first time, working on a project that is slightly bigger in scale. Within my Firestore database, I have a collection with three documents. My goal is to extract the document IDs and store them in an array. The component responsible for this task is structured as follows:

<template>
  <div class="main">
    <button @click="getIds" class="nextBtn">Next</button>
  </div>
</template>

<script>
import { computed } from 'vue';
import { useStore } from 'vuex'

export default {

setup() {
  const store = useStore();
  const questdb = computed(() => store.state.questdb);
  let idArray = [];

  function getIds() {
    this.questdb.onSnapshot(function(doc) {      
      doc.forEach(doc => {
        try{
          this.idArray.push(doc.id);
        }
        catch(error) {
        console.log("Error: ", error);
        }              
      })
    })
  }
  return {
    store,
    questdb,
    idArray,
    getIds
  }
},
  methods: {
  }
}
</script>

An error message appears stating:

TypeError: Cannot read property 'push' of undefined

If I simply console.log() the document IDs, everything works smoothly.

It seems like there may be an issue with how data is being added to the array or perhaps I need to deepen my understanding of retrieving data from Firestore.

Answer №1

Avoid using 'this' before idArray because it does not contain an idArray, resulting in 'undefined'. Here is a suggested alternative approach:

function fetchIds() {
questdb.onSnapshot(function(doc) {      
  doc.forEach(doc => {
    try{
      idArray.push(doc.id);
    }
    catch(error) {
    console.log("Error: ", error);
    }              
  })
})

}

For more information, refer to the Vue composition API documentation. https://v3.vuejs.org/api/composition-api.html#setup

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

Generate and animate several HTML elements dynamically before deleting them in a Vue2 application

When using Vue 2 (and Nuxt), I am trying to achieve a specific animation effect on button click. The animation involves a "-1" moving up a few pixels from the button and disappearing after a second. The challenge is to have multiple "-1" animations happeni ...

Encountering an error with Next.JS when using the "use client" directive

Recently encountered a bizarre issue with my next.js project. Every time I input "use client"; on a page, it triggers a "SyntaxError: Unexpected token u in JSON at position 0". Here's the code snippet for reference: "use client" ...

Identifying the moment when the hide() function in jQuery is triggered for an element

Is there a way to detect when the .hide() method in jQuery is triggered on an element? I attempted to attach an event listener to the hide event of that particular element: $('div').bind('hide', function(){ alert("Hidden&q ...

What are the benefits of sticking with Express versus transitioning to a combination of JavaScript and HTML?

Recently, I've been developing a web application that involves taking user input to make modifications to files on the server side. The main logic for this project is built in node.js and operates via command line, with the rest of the site being deve ...

How to Retrieve Grandparent Component Attributes in Angular Using Grandchild Components

I am constructing an Angular application and facing the challenge of accessing a property of Component 1 within Component 3. In this scenario, the relationship is described as grandparent-grandchild. Successfully establishing communication between parent/ ...

Understanding XML parsing problems

I've decided to keep the live xml/atom-feed URL private, as it's hosted on LiveJournal. However, I'm a bit confused about how this all works: let XML_URL = "https://users.livejournal.com/<username>/data/atom"; $(function(){ ...

Transform a text node into an HTML element with the help of JQuery

Consider this HTML snippet: <div> Lorem ipsum <span>dolor sit</span> amet <span>consectetur adipiscing elit</span> eiusmod tempor </div> To select the text nodes [Lorem ipsum, amet, eiusmod tempor], ...

When clicking on the input file, the onChange event will be triggered just once

I am currently experiencing an issue with my code. Whenever the "simulateClickBtn" function is invoked, a system popup emerges prompting to choose a file. Upon selecting the file, it proceeds to the callback and executes the sendMessage function successfu ...

Retrieve the value from a classic ASP page using an if statement and pass it to

Currently, I am attempting to assign a JavaScript value through ASP. foo('RequestMode', '<%=Request.Querystring("Mode")%>') My goal is to achieve something along the lines of: foo('RequestMode', '<%=if (Reques ...

AngularJS implementation for a confirmation dialog with data

I need help creating a confirmation dialog box for user action verification. Here's the situation: I have a table with multiple events, and users can choose to delete an event. This is how the table is structured: <tbody> <tr ng-repeat= ...

Animate CSS Grid to dynamically fill the viewport on top of current grid elements

Please note that I am specifically seeking vanilla JS solutions, as jQuery is not compatible with this project I have a grid structure that is somewhat complex: body { margin: 0; height: 100vh; text-align: center; } .grid-container { ...

Passing the $scope variable between functions

Here is the function in my angular controller: $scope.selectinteresteduser = function(Id){ $scope.selecteduserid = Id; } $scope.sendMessageToEmployeer = function($scope.selecteduserid) { alert($scope.selecteduserid); } I am looking for a way to pa ...

What are some techniques to ensure null checking is enforced for objects that are nested within multiple layers

Currently, I am leveraging redux sagas to fetch data asynchronously from various endpoints using a unified interface: export interface ResponseInfo { data?: any; status: number; headers?: any; subCode?: string; } To ensure that null check ...

Incorporate content upon button click using Javascript

Looking to create a unique Survey layout that includes: Question Name Options The question name is editable and can be changed with a click. Initially, there is one option with a checkbox to select it. This option should also update when clicked. Addit ...

Using Socket.io with NGINX has been quite a challenge as I have been struggling to properly configure the sockets

Having my backend set up with socket.io, I wanted to configure socket.io with nginx. Despite configuring nginx with the following settings, my routes other than sockets are functioning properly but my sockets are not working. server_name yourdomain.com ww ...

Encountering trouble setting up an express server on Vercel with a 404 page error

I encountered an issue with deploying my express server on Vercel in order to resolve the CORS problem with my frontend code. When I try to access the deployed page, I am getting a 404 error: However, everything works fine when I test it on localhost. // ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

The issue with Vue email validation not functioning correctly when the div ID is removed

I'm completely new to Vue.js and I'm keen on understanding why removing the div with id "app" in this codepen example (not mine) leads to the failure of rendering the email validator input field. <div class="container" id="app&q ...

When the icon is clicked using `ngClick`, we are triggering the `refresh` event, but unfortunately, it is not functioning as expected

Currently, I am utilizing Angular and jQuery float to create a canvas graph. The graph itself is composed of canvas elements. The issue at hand involves the desire to redraw the canvas upon clicking on a specific icon. The click event handler in question ...

Unable to deploy the Firebase function to Firebase functions platform

I've been watching Doug's video on YouTube for guidance on changing a message with functions in JavaScript. To resolve the error message 'types can only be applied to ts files,' I installed the Flow language script. Thankfully, that err ...