[Vuejs]-Vue.js: Data is not reactive and not correctly updated within a method

3👍

As @user1521685 has already explained, the call to fetchDoctors is asynchronous so it’ll complete after you’ve performed the filtering.

Typically you’d do something like this using a computed property instead and only make the server call once.

export default {
    data: () => ({
        allDoctors: [],
        filters: []
    }),
    computed: {
        filteredDoctors() {
            const allDoctors = this.allDoctors;
            const filters = this.filters;

            if (filters.length === 0) {
                return allDoctors;
            }

            return allDoctors.filter(doctor => {
               return filters.some(filter => filter.specialty === doctor.specialty || filter.city === doctor.city);
            });
        }
    },
    methods: {
        fetchDoctors(){
            //Retrieve doctors
            this.$store.dispatch(RETRIEVE_DOCTORS)
            .then(
                response => {
                    this.allDoctors = response;
                }
            )//TODO-me: Handle the error properly!
            .catch(error => {
                console.log(error);
            });
        },
        showFilteredDoctors(filters){
            this.filters = filters;
        }
    },
    mounted() {
        this.fetchDoctors();
    }
}

In your template you’d then use:

v-for="doctor in filteredDoctors"

2👍

fetchDoctors is async, so in showFilteredDoctors you fetch the doctors, then set the filtered array and then the thenable in fetchDoctors kicks in and overrides the doctors again: this.allDoctors = response.
You’d have to return the Promise in fetchDoctors and use it in showFilteredDoctors like so:
this.fetchDoctors().then(() => /* do the filtering */)

EDIT: Return the Promise like this:
return this.$store.dispatch(RETRIEVE_DOCTORS).then().catch()

Leave a comment