Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuex, changing state in an action

I'm trying to code as "good practice" as possible while learning Vuex.

From what I learning I tought that Actions are used to do for example external API calls, the result of that is passed to a Mutation via a commit().

Now I want to increment a counter for a certain user on Firebase. This is working when I code my action like this

    ADD_CREDIT(context, user) {

        user.credits++;

        firebase.database().ref('users').child(user.id)
            .update({credits: user.credits})
            .then(() => {});

    }

So in my action I already update the state before calling the API call. Is this good practice? I tried it the other way using the following code, but that just looks to complicated.. And it doesn't work for now.

Action

ADD_CREDIT({commit, state}, user) {

        const newcredits = user.credits + 1;

        firebase.database().ref('users').child(user.id)
            .update({credits: newcredits})
            .then(() => {
                commit('CREDIT_CHANGED', user.id, newcredits)
            });

    }

Mutation

CREDIT_CHANGED(state, userid, newcredits) {
        let user = state.users.find(user => {
            return user.id = userid
        });

        user.credits = newcredits;
    }
like image 417
Miguel Stevens Avatar asked Nov 03 '17 20:11

Miguel Stevens


1 Answers

The pattern of a mutation function is

function mutation(state, payload) {
...
// do something with state
state.person = payload;
...
}

It doesn't have anymore argument than that 2.

So, your mutations should pass an object with all of your information. Like this:

CREDIT_CHANGED(state, payload) {
   let user = state.users.find(user => user.id === payload.userid);
   user.credits = payload.newcredits;
}

And then you action should commit like this:

ADD_CREDIT({commit, state}, user) {

    const newcredits = user.credits + 1;

    firebase.database().ref('users').child(user.id)
        .update({credits: newcredits})
        .then(() => {
            commit('CREDIT_CHANGED', {
                 userid: user.id, 
                 newcredits: newcredits 
            })
        });

}
like image 171
Lucas Katayama Avatar answered Sep 19 '22 18:09

Lucas Katayama