Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

commit method redundancy? #4

Open
alecgregory opened this issue Jun 3, 2021 · 1 comment
Open

commit method redundancy? #4

alecgregory opened this issue Jun 3, 2021 · 1 comment

Comments

@alecgregory
Copy link

Thanks for this article, very informative and inspiring.

Could you explain the apparent redundancy between the mutation functions and the store's commit function?

For example, the addItem mutation is defined as:

addItem(state, payload) {
  state.items.push(payload); // store's state is updated after this runs

  return state;
}

This updates the store's state but the commit method then updates the state again:

commit(mutationKey, payload) {
  let self = this;

  if (typeof self.mutations[mutationKey] !== "function") {
    console.log(`Mutation "${mutationKey}" doesn't exist`);
    return false;
  }

  self.status = "mutation";

  let newState = self.mutations[mutationKey](self.state, payload); // state is updated after this runs 

  self.state = Object.assign(self.state, newState); // this update appears to be redundant as self.state already reflects newState

  return true;
}

One reason I can think for this is that a particular "mutation" might only return a new state object rather than manipulating the object it was passed e.g.

addItem(state, payload) {
  return { ...state, items: [...state.items, payload] }; // store's state is not changed by this so the update in the commit method is required
}

but the definition of a mutation in the article clearly states that mutations should update state ("mutations should always be simple because they have one job: mutate the store’s state"), so I'm not sure there's a need to code for this case.

@Lord-Leonard
Copy link

Lord-Leonard commented Jan 24, 2024

I found the difference quiet confusing as well but I found this Blog Post about the actions and mutations in Vuex (state management in Vue, i guess)

In Vuex actions are used to group mutations and "commit mutations".

actions: {
  loadBooks({ commit }) {
    commit('startLoading');
    get('/api/books').then((response) => {
      commit('setBooks', response.data.books);
      commit('stopLoading');
    });
  },
},

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants