Reputation: 85
I am trying to concat 2 arrays of arrays, but there is no effect because of async fetching one of them.
this.subcategories = [...this.subcategories, ...[ this.$store.getters['categories/subcategoriesOfCurrent'] ]];
Getter above is being set after some ms (server response) so when this assignment is triggered, getter is empty. When state is set (server responded), array 'subcategories' should be updated but it is not (but getter is). How to solve it?
More code:
getter:
subcategoriesOfCurrent: (state: CategoriesState, getters: any) => {
return (getters.current && getters.current.subcategoryIds) ?
getters.current.subcategoryIds.map((id: string) => getters.all[id]) : [];
}
actions:
setCategory: ({ commit, dispatch }: ActionArgs, categoryId: string) => {
commit('setCategory', categoryId); //sets current category Id
dispatch('fetchSubcategories', categoryId); //fetching from server which commits updateCategorySubcategories
},
fetchSubcategories: ({ dispatch, commit }: ActionArgs, parentId: string): void => {
HttpService.getInstance().get(`/categories?parent_id=${parentId}`).subscribe(
result => {
commit('updateCategories', result.data);
commit('updateCategorySubcategories', { parentId, categories: result.data });
}
);
},
mutation which updates subcategoryIds:
updateCategorySubcategories: (state: CategoriesState, { parentId, categories }: { parentId: string; categories: Category[] }): void => {
Vue.set(state.categories[state.currentCategoryId], 'subcategoryIds', categories.map(category => category.id));
},
Upvotes: 0
Views: 191
Reputation: 17930
Create a computed for the subcategories:
computed: {
subcategories() {
return [...this.subcategories, ...[ this.$store.getters['categories/subcategoriesOfCurrent'] ]];
}
}
since computed props are reactive, it will change the result each time the getter changes
Upvotes: 1