DEV Community

Discussion on: Mapping for a Vuex beginner

Collapse
 
napoleon039 profile image
Nihar Raote

The reason is similar to why we have mutations at all when actions do the same work. If we change the state directly, it will mean the state can be modified/mutated from anywhere, making it hard to find where exactly a particular modification comes from.

Mutations provide a way to centralize all the state mutations. And since the state can't be updated asynchronously, we have to use mutations which are synchronous instead of actions, which can be asynchronous.

Mutations are meant to fulfill a very small part - provide a single place to mutate the state from. Actions, on the other hand, handle all the other logic which can be asynchronous.

Read this answer on StackOverflow about why mutations are needed in spite of having actions.

I hope this answers your question. If you have anything else to ask, feel free to ask away 😃

Thread Thread
 
mattarc profile image
mattarc

Thanks for the response, Nihar. I understand the need for mutations in the way that as you say we have asynchronous actions for synchronous mutations. But essentially, yes you have hit the nail on the head in your first reply to my comment,
"why is there a need to map mutations in a Vue component since we can just map actions because mutations are, in the end, committed by actions?"
This I still don't understand. It seems to me that a mapped action would commit the mutation in the store; there would never be a need to call a mutation from a mapping?

Thread Thread
 
napoleon039 profile image
Nihar Raote

I honestly haven't found an answer to it as well. It's like no one else wonders why we need to commit mutations in the store when we can dispatch an action for it. But since there's an example for mapping mutations in the component in the Vue documentation, there should be a reason.

Though I haven't seen this reasoning anywhere I think it's because an action is expected to do some asynchronous stuff along with committing mutations. So maybe a use case for committing mutations in the component is when actions do more than just commit mutations and we only need to commit a mutation and not the other stuff?

I'll try to see if there is an answer anywhere like Stackoverflow or ask on Twitter if I still can't find one.