DEV Community

Zyrianov Viacheslav
Zyrianov Viacheslav

Posted on • Updated on

Vue store action: commit or return data?

Based on my experience, there are some things that may be useful for novice Vue developers. This time, I want to share with you some info about how to manage response data from API, based on context of using actions.

There are 2 basic ways, how you can manage response data from action in store:

  • commit into state
  • return instantly

But how to choose, when to use what?
If you want to use data from API anywhere in application e.g. in another store module, vue-component or any other JS file and it is used in multiple files, then you should commit data in state. In that case the data will be available anywhere in application.

For example, when you retrieve user data, it may be used on user account page and in header to show user name and last name. It means, that response will be used in different components. It can be even requested in completely different component, like App.vue.

If the data from action is being used as soon as being requested – you should return the data instantly as it was requested.

For example, there is list of social links, that are being passed from API and being rendered only in footer. So why do we need to save response data in state? We can simply return it from action and instantly use it in Footer.vue component.

Another case is dynamic component. What exactly do i mean? If there is component, like news item, that is being rendered only based on specific request, you don’t need to store data in state. Instead of it – simply return data from action, store it in this component!

Why should it has been done like that? There are two reasons for it:

  • Store won’t be littered with unnecessary data
  • Store will feel itself more freely and developer will have much less data in store module

In conclusion, i will say that both approaches are actually legal, but by using return you will not litter store.

See you later <3

Top comments (0)