vuex actions that do not need to commit a mutation
Asked Answered
W

2

13

Using Vue and Vuex, I have followed the recommended practice of making changes to state only via mutations. So all Vue components will make changes to state via the use of an action which then in turn commits a mutation. I also make API calls in some actions which then update state based on the result.

I now have some API calls that do not need the state to be updated after they are called. Question is should I still use actions? or should I bypass vuex and make those calls directly from components?

Widgeon answered 3/10, 2018 at 15:40 Comment(0)
P
24

The main reasons for using actions are these:

  • mutations have to be synchronous, actions can be asynchronous -> If you want to deal with asynchronous operations before a mutation, you have to use an action
  • if you want to commit multiple mutations at once, you can bundle them logically into one action

So in conclusion, you are right: If it is clear to you that these API calls do not alter the application's state in any way, they shouldn't be called by using actions.

Make those calls directly inside your components, import a module holding the needed functions or put the respective methods into a mixin if you want them to be shared between multiple components.

If you should, however, find out during development that the result of these calls should be shared between multiple components of your application, move the respective logic to the store via actions and mutations.

Psychogenic answered 9/10, 2018 at 14:17 Comment(3)
Also, I observed that if you do an async operation in an action and directly mutate state without commiting it (using commit()) then Vue devtools will not show updated state values (as result of the async operation). This is what I observed at least on one instance. Pls correct if this isn't the case.Biometry
i ran out with this "problem" too, my way to deal with it is myfunction({},payload). This way i not disturb the state, i dont know if this is a good practice, you people know a best way?Longshoreman
It seems to me that using _ instead of {} is the convention for indicating to other programmers that they should "ignore this binding/parameter", so myfunction(_, payload). #27637513Ticktack
V
8

you can use _ instead of {commit}

getAllUser(_, payload) {
    let response = await ApiService.getAllUser(
        payload.params
    );
    return response;
}
Vallie answered 5/12, 2021 at 11:56 Comment(3)
Where is this documented?Police
Found a similar question elsewhere https://mcmap.net/q/903785/-vuex-action-handler-context-object-and-payload-eslint-rules-problemPolice
For me this makes vue more messy and messier. This is the kind of semantic candy that makes applications more and more obscure and does not add performance. I call this sort of shortcuts an anti-patternSanative

© 2022 - 2024 — McMap. All rights reserved.