Vue seems to be experiencing some difficulty displaying the data

I am facing an issue with loading data from firestore asynchronously. Although I can see the data in the log, Vue is only displaying the initial value before the data is loaded.

I have tried calling the loading method both using beforeMount() and from a click of the button.

It seems like I'm missing some fundamental piece here - any help would be greatly appreciated!

<template>
  <div class="pt-3">
    <v-row class="d-flex justify-center">
      <v-col cols=4>
        <v-text-field
          label="New Land"
          outlined v-model="newItem"
          @keyup.enter="addItem"/>
      </v-col>
      <v-col cols=4>
        <v-text-field
          label="Region"
          outlined v-model="newRegion"
          @keyup.enter="addItem"/>
      </v-col>
    </v-row>
    <v-row class="d-flex justify-center">
        <v-col cols=6>
          <v-btn color="primary" @click="addItem">Add Land</v-btn>
      </v-col>
    </v-row>
    
    <v-row class="d-flex justify-center">
        <v-col cols=6>
          <v-btn @click="getGeoHierarchy('Geographies',0,0,[])">Fetch Geographies</v-btn>
      </v-col>
    </v-row>
    <v-row>
        {{vGeoData}}
        <v-col>
            <v-card v-for="(geography,id) in vGeoData" :key="id">
                <v-card-title>{{geography[0].name | capitalize }} </v-card-title>
                <v-card-text>  tests</v-card-text>
            </v-card>
        </v-col>
    </v-row>
  </div>
</template>


<script>
import { db } from '../firebase/db'
export default {
    async created(){
        
    },
    beforeMount(){
        this.getGeoHierarchy('Geographies',0,0,[]);
    },
    data() {
        return {
            Geographies:[],
            newItem: "",
            newRegion:"",
            vFirst:true,
            vTopLevel:0,
            vGeoData: [''],
            vToplevelData: [],


        }
    },
    filters: {
        capitalize: function (value) {
            if (!value) return ''
            value = value.toString()
            return value.charAt(0).toUpperCase() + value.slice(1)
        }
    },
    methods:{
        async addItem() {
            if(this.newItem && this.newRegion) {
                var docData = {
                    name: this.newItem,
                    regions : {
                        name: this.newRegion
                    }
                };
                await db.collection("Geographies").add(docData);
                this.newItem ="";
                this.newRegion = "";
            }
        },
        deleteItem(id){
            db.collection("Geographies").doc(id).delete();
        },
        async getGeoHierarchy(vPath,vStep,vCounter,vGeographies){
        
            console.log(vPath)
            const vTempGeo = [];
            await db.collection(vPath)
                .get()
                .then(function(querySnapshot) {
                    querySnapshot.forEach(function(doc) {
                        // doc.data() is never undefined for query doc snapshots
                        const vCollections = doc.data().collections;
                        vTempGeo.push({
                            name: doc.data().name,
                            id: doc.id,
                            collection: vCollections,
                            path: vPath + "/" + doc.id,
                            level: vStep,
                        })
                        return vTempGeo
                    });
                });
                
            //debugger;
            console.table("vGeographies:",vGeographies);
            for(let i=0; i<vTempGeo.length;i++){
                vGeographies.splice(vCounter+i,0,vTempGeo[i]);
                // debugger
            }
            const lGeographies = vGeographies.length;
            for (let i=vStep; i<lGeographies;i++){
                const vCurrent = vGeographies[i];
                //debugger
                if(Array.isArray(vCurrent.collection)){
                    
                    for(let j=0; j < vCurrent.collection.length; j++){
                        await this.getGeoHierarchy(vCurrent.path+"/"+vCurrent.collection[j],vStep+i+j+1,vCounter+1,vGeographies);
                    }
                }
            }
            console.log("this.Geographies",this.Geographies);
            console.table("vGeographies:",vGeographies);
            // debugger
            this.Geographies = vGeographies;
            this.populateGeoData(0);
            return this.Geographies
            
        },
        populateGeoData(vTopLevel) {
            console.log('--populateGeodata','start')
            console.table("this.Geographies:",this.Geographies);
            let vTempArr = [];
            let vTopLevelData = [];
            let vTempGeo = [];
            
            let vFirst = true;
            let vTopLevelCounter = 0;

            
            for(const geography of this.Geographies){
                console.log("geography:", geography)
                const last = (this.Geographies.length-1 == this.Geographies.indexOf(geography))
                // debugger
                if(!vFirst){
                    if(geography.level==vTopLevel){
                        vTempGeo[0] = vTopLevelData
                        vTempGeo[1] = vTempArr;
                        this.vGeoData[vTopLevelCounter] = vTempGeo;
                        vTempGeo = [];
                        vTopLevelData = geography;
                        vTempArr = [];
                        vTopLevelCounter++;
                    }
                    else {
                        vTempArr.push(geography);
                    }
                }
                else {
                    if(geography.level == vTopLevel){
                        vTopLevelData = geography;
                        vFirst = false
                    }
                    else{
                        console.log("populateGeoData", "First is not toplevel")
                        vTempArr.push(geography)
                    }
                }
                if(last){
                    if(geography.level == vTopLevel){
                        vTempGeo[0] = vTopLevelData
                        vTempGeo[1] = vTempArr;
                        this.vGeoData[vTopLevelCounter] = vTempGeo;
                    }
                    else {
                        vTempArr.push(geography)
                        this.vGeoData[vTopLevelCounter] = vTempGeo;
                    }
                }
               
            }
           
            console.table("vGeoData:",this.vGeoData)
            console.log('--populateGeodata','end')
            return this.vGeoData;
        }
    },
    firestore: {
        Geographies: db.collection("Geographies")
    },
    mounted(){
        
    },
    watch:{
    }
}
</script>
<style lang="stylus">
    .grape {

    }
</style>

THANKS

Answer №1

One approach is to utilize async mounted and move your data loading logic there. With the assistance of vue devtools, you can easily examine your app's state to pinpoint the source of any bugs.

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 there a way to utilize a value from one column within a Datatables constructor for another column's operation?

In my Typescript constructor, I am working on constructing a datatable with properties like 'orderable', 'data' and 'name'. One thing I'm trying to figure out is how to control the visibility of one column based on the va ...

UI-Router is failing to transition states when $state.go() is called

I am currently troubleshooting a unit test for my user interface router routes, specifically focusing on the issue I encountered with the test not passing successfully. Within my test script, when checking the value of $state.current.name, it returns &apo ...

Angular Selectable Drop-down Menu

I'm facing an issue with using angularjs for dropdown with multiple selection. When I try to include 2 dropdowns in the same form, only one of them gets initialized properly. Here is a sample code snippet http://jsfiddle.net/vUSPu/1221/. Can someone p ...

Decoding the Language of HTTP Status Codes

Let's imagine a scenario where I create a file called api.js: const {somefunction} = require('../controllers/some-controller'); app.get('/data/', somefunction); In my some-controller.js: exports.somefunction = async (req, res,next ...

Is it possible to categorize elements for focus and onblur events?

In my search feature, I have implemented an autocomplete div that appears when the user types in a search field. The issue I am facing is that I want the div to disappear when the user clicks outside of it. Here is what I have attempted: //SHOW THE DIV WH ...

Employing VAutocomplete component from vuetify in combination with a render function (scoped slot)

Trying to implement the Autocomplete component within a render function but encountering issues with the scopedSlots feature. Here is my code snippet: import { VAutocomplete } from 'vuetify/lib' export default { render (h) { return ...

Accessing/Storing Pictures in MongoDB using Mongoose

I've been struggling with managing images in MongoDB for a while now. Everywhere I look suggests using GridFS because of the 16mb size limit per document. However, the documents I want to store are all <16mb each. Currently, I am storing it like th ...

Using an action code to retrieve the current user from firebase: A step-by-step guide

I am in the process of designing 2 registration pages for users. The initial page prompts the user to input their email address only. After they submit this information, the following code is executed: await createUserWithEmailAndPassword(auth, email.value ...

Looking to retrieve the checkbox value from HTML in AngularJS and pass it to the controller

How can I retrieve the value of a checkbox on button submit in a controller Function? <input id="Check" type="checkbox" ng-model="CheckValue" /> ...

Eliminate repeated elements by comparing two sets of data

I have two arrays of data, rlT and refundT. My goal is to eliminate any duplicate items from the rlT array that have a matching transactionId in the refundT array. I came across a solution using filter() and find() on Stack Overflow: Remove all elements co ...

Best practices for retrieving information from the user interface

My journey with NextJS has been a learning experience as I navigate connecting the frontend to the backend. Initially, I attempted to create a Restful API for CRUD operations from the frontend, but encountered authentication issues that left me puzzled. A ...

Retrieve data from MongoDB using the find() method results in an empty response, however,

While working on a project to practice my MongoDB skills, I encountered an issue with retrieving all the data from MongoDB. Despite receiving a successful 200 response, I was unable to properly extract all the data. Using Express framework for this task, ...

Discovering the present route within the Vue 2.7 composition API

When working with Vue2, I am able to access the current path using this.$route.path In Vue3, I can utilize useRouter() for similar functionality. However, inVue2.7 composition api, neither of these options is available. ...

Creating a MySQL table that includes long string data types

Recently, I was working on creating an online forum and encountered a problem with the writing function. The form consists of a title and content section, which usually functions properly. However, when I enter a slightly longer text in the content field, ...

What is the best way to independently trigger changes in multiple copies of a Component?

Is there a way to use a computed property to trigger a boolean value within a component without impacting other copies of the same component? I have multiple instances of this component and want each one to trigger independently based on specific conditi ...

Obtain the textfield whenever the user desires

I have added an image upload file field in the form. If the user wants a multi-select field, I want to allow the user to choose the number of files they want to upload. Take a look at my text field below: <div class="form-group col-lg-10"> {! ...

The issue arising where the callback function fails to execute after making an AJAX POST request

Within my function, I have an AJAX call that I want to make reusable. When the AJAX call is successful, I need to callback a function. var ajaxPostCall = function(data , url ,callback){ // Return the $.ajax promise $.ajax({ data: data, dataType: ...

Is it possible for me to overlap a text over hidden text, and if the hidden text becomes visible through JavaScript, my text will shift to the right of the now visible hidden text?

I'm currently working on a website for a company that requires users to complete all the information before proceeding. To achieve this, I created a form with the following code: <form action="Owners Infoback.php" onsubmit="return validateFo ...

Exploring the process of querying two tables simultaneously in MySQL using PHP

I currently have a search box in my PHP file that only searches from the "countries" table. However, I also have another table called "continent" and I would like the search box to retrieve results from both the "countries" and "continent" tables. Here is ...

Using vue-class-component: A guide on creating and setting up reactive data

I am currently working with Vue.js using TypeScript and vue-class-component. My goal is to create a custom component with reactive data. Below is the code I have so far: <template> <div> <input v-model="data.name" placeholder=" ...