0
votes

i have a problem with vuex.

My store looks like this:

state: {
    ...
    client: {
        name: '',
    },
},
mutations: {
    ...
    SET_CLIENT: (state, client) => {
    state.client = Object.assign({}, client);
    },
},
actions: {
    ...
    set_client({ commit }, { client }) {
        commit('SET_CLIENT', client);
    },
},
getters: {
    ...
    client: state => state.client,
},

In my vue router i check every route if 'client_id' in my params. If true i send a request with axios to a server to get client data:

router.beforeEach((to, from, next) => {
    if ('client_id' in to.params) {
        const id = to.params.client_id;

        axios.get('client/' + id).then((response) => {
            const data = response.data;
            store.dispatch("set_client", data);
        })
        .catch((error) => {
            console.log(error);
        });
    }
    
    next();
})

In the component that loaded with the next() statement, i print client.name in the template. For example:

<template>
    <div>
        ...
        <v-card-title>{{ $store.getters.client.name }}</v-card-title>
        ...
    </div>
</template>

But the card title remains emtpy.

Why?

For other data, for example a array of clients, thats work very well..

1
I met the same issue before, try use state.client = JSON.parse(JSON.stringify(client)) instead of Object.assign to see if it worksJeremy Su
why not using simple assignation like state.client = client payload ?petitkriket

1 Answers

0
votes

Try using Vue.set() in the mutation. You assign a new Object to the store. This is not gonna be reactive and therefore you don't see the new value. https://vuejs.org/v2/guide/reactivity.html

mutations: {
    ...
    SET_CLIENT: (state, client) => {
    Vue.set(state.client, {...client})
    },
}