[Vuejs]-Array in data method gets updated in one method but still empty in another method

1👍

I think a key missing part may be updating the component’s exerciseList variable , not the list argument. They are not the same variable. Objects are passed by reference but arrays are passed to functions by value only which makes list it’s own variable independent from excerciseList. This is rough code that shows some ways to make sure exerciseList is updated and how to know when the values are all in the array.

// include exerciseListLoaded to flag when all data is ready
data: () => ({
    exerciseList: [],
    exerciseListLoaded: false
});

created() {
    this.getDataBaseCollection("Exercise"); // array gets information here
}
mounted() {
    // based on timing of the `onSnapshot` callback related to `mounted` being called, this may likely still result in 0
    console.log("Mounted");
    this.getExercises();
},

watch: {
    // watch for all data being ready
    exerciseListLoaded () {
       console.log("All Loaded");
       this.getExercises();
    }
},

methods: {
    // be sure to update the exerciseList on the component
    getDataBaseCollection: function (CollectionName) {
        // being careful about `this` since within `onSnapshot` I suspect it will change within that function
        const componentScope = this;
        db.collection(CollectionName).onSnapshot(snapshot => {
            snapshot.forEach(doc => {
                componentScope.exerciseList.push(doc.data());
                // could also still update `list` here as well if needed
            });
            // setting this allows the component to do something when data is all loaded via the `watch` config
            componentScope.exerciseListLoaded = true;
        });

    },

    getExercises: function () {
        console.log(this.exerciseList.length);  // length is 0 ?? array seems empty
    }
 },

-1👍

when you use this inside a function it refers to the function not the vue instance so you may use that may work with you:

getExercises() {
        console.log(this.exerciseList.length);  
    }

Leave a comment