Vencho
Vencho

Reputation: 163

Best way to update state

In my application's state, I have a teacher's list, which is never empty. That piece of state, is used in two different views, that the user can go directly (they don't have to go to page1 and then to page 2, they can go directly to page 2 if they want to, or they can go to both). So my question is ¿How should I set the state? (I'm using vuex)

So far, I've came across 2 solutions, but I don't think they are the best ones:

  1. Set the state every time I need to access the property. (maybe with a getter and doing something like if(store.getters.teachers.length < 1) await dispatch('SET_TEACHERS'))
  2. Having that logic in the action SET_TEACHERS() { if(state.teachers.length < 1) //Api call }

I don't like the first one because the data won't change that often, and the second might be OK, but I'm not sure.

Upvotes: 0

Views: 242

Answers (1)

Luciano
Luciano

Reputation: 2196

I'm facing a similar situation right now. My vuex state should be available in N views/components and fetching data whenever a component is mounted is a waste of resources. Besides that, you will lose the most important vuex usability by coupling your vuex store with your components.

I recommend you to decouple your vuex from your views by hydrating your state out from any child component (IE your App.vue) and just mapping your state in children components.

You may wonder then how to update your state if anything changes. Well, this is the tricky part. If you are working with your own API Rest you can emit a WebSocket event. Then, you can listen to that event and dispatch your SET_TEACHERS as per the payload received from API.

Believe me, I'm just an amateur with WebSockets but it's saving me a ton of time and the user experience is awesome.

Hope it helps to give you a different point of view on your situation.

Upvotes: 1

Related Questions