wawanopoulos
wawanopoulos

Reputation: 9794

VueJS/VueX : Watch never called when state property is an array

I have a simple flow that consist to:

Problem is that my watcher is never called on my component.

VueX module:

/*
 * State: properties to store
 */
const state = {
    siteCars: []
};

/*
 * Getters: Getters of properties defined in state
 */
const getters = {

    siteCars(state) {
        return state.siteCars;
    }

};

/*
 * Mutations (Setters): Setters of properties defined in state
 */
const mutations = {

    PUSH_CARS(state, data) {
        state.siteCars = _.merge(state.siteCars, data.cars);
    },

};

/*
 * Actions
 */
const actions = {

    /*
     * Action used to create multiple cars
     */
    massImportCars({ commit, rootState }, payload) {

        axiosBackend.post("/cars/massimport", payload,
            {
                headers: { Authorization: rootState.auth.authString }
            }
        ).then(res => {

            commit("PUSH_CARS", {
                cars: res.data.data
            });

        }).catch(error => {});

    },

};

export default {
    state,
    getters,
    mutations,
    actions
};

In my Vue Component:

I just declared a watcher on my siteCars property which come from a getter inside the VueX module. Problem is that the handler is never called when new cars are pushed to the siteCars state.

watch: {
   siteCars: {
      handler(val){
         console.log("NEVER CALLED !!");
      },
      deep: true
   }
},
computed: {
   ...mapGetters(["siteCars"]),
},

Upvotes: 1

Views: 1111

Answers (2)

user1935987
user1935987

Reputation: 3347

if you need to merge 2 arrays, solution with ES6 spread operator

state.siteCars = [...state.siteCars, ...data.cars];

Upvotes: 1

Mohsin Amjad
Mohsin Amjad

Reputation: 1209

Try changing your mutation as

state.siteCars.push(data.cars);

so it doesn't change the reference of your previous state

Upvotes: 1

Related Questions