Answer the question
In order to leave comments, you need to log in
How to properly organize data fetch in Unidirectional Data Flow?
The question is quite abstract, here is its essence:
1. Suppose there is a certain set of entities, Entities. When loading the SPA in one way or another, I go to the API for these entities, /v1/entities/, I get an array of models in response, which I immediately push into the store.
2. When a user follows a link to an entity page, I reasonably assume that he has already loaded this entity (otherwise he would not have seen the link), which means I simply execute action dispatch in the store, saving the identifier of the selected entity. Accordingly, when I need to display the details of an Entity, I simply do a find on the stored array of models.
3. There is a scenario in which the user received a link to a SPA page with the details of an entity that he does not have (and which will not load itself, for example, due to paging). In that case, I need to be able to query with the /v1/entities/N API.
Now the question is when should this be done?
Spherical storage in a vacuum looks like this:
export default {
state: {
entities: null,
selectedEntityId: null
},
getters: {
entities: state => state.entities,
selectedEntity: state => state.entities && state.entities.find(e => e.id === state.selectedEntityId)
},
mutations: {
recieveEntities (state, { entities }) {
state.entities = entities
},
selectEntity (state, { entityId }) {
state.selectedEntityId = entityId
}
},
actions: {
async fetchEntities ({ commit }) {
let { data } = await axios.get('http://myapi.com/v1/entities')
commit('recieveEntities', { entities: data })
},
selectEntity ({ commit }, { entityId }) {
commit('selectEntity', { entityId })
/*
в теории здесь мне нужно делать запрос на сервер за деталями сущности
но чтобы не делать запрос вхолостую, нужно уметь предсказывать,
будет ли в соседнем action нужная мне entity, что сделать невозможно, ибо запрос асинхронный
*/
}
}
}
Answer the question
In order to leave comments, you need to log in
In this case, I do either in the router route: { ... beforeEnter() ... } or in the component that opens on it beforeCreate(), or created(), as it is more convenient, request the data of this entity using dispatch(' get-entity', id) for example.
If it is in the array in the storage, we return it immediately, set the loading animation trigger to false, if not, we do an action that pulls it along the api and adds it to the array. At the start of this action is a loading animation trigger.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question