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;
}
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
})
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With