Hi everyone I was struggling with calling dispatchers
and getters
in composition API in vuex.
Below is my store :
// state
items: Item[] = [];
// getters
get getItems(): ComputedRef<Item[]> {
return computed(() => this.items);
}
// mutations
@Mutation
commitSaveItems(items: Item[]) {
this.items = items;
}
// actions
@Action
async dispatchGetItems(): Promise<boolean> {
const response: Response = await this.api.getItems();
const items: Item[] = response.data;
console.log(items);
this.commitSaveItems(items);
return true;
}
composables as :
export function allItems(): ComputedRef<Item[]> {
const items = itemStore.getItems;
return items;
}
export async function getItems(): Promise<boolean> {
return itemStore.dispatchGetItems();
}
component as :
setup() {
getItems();
let items = allItems();
return {items}
}
I am aware that I cannot call getItems() -> that is calling my API and getters both in setup but I am completely clueless how to do this.
I want that initially my API fetch the items and bind items state and then my getter able to show my items in my template. any help will be appreciated
For anyone else stuck in the same, I got the following workaround for now:
As we don't have beforeCreated
and Created
in Composition API it is replaced by setup. So I call my dispatcher in onBeforeMounted
my updated and working code is as follows :
setup() {
let items: ComputedRef<Item[]> = computed(() => []);
onBeforeMount(async () => {
await getItems();
items = allItems();
});
}
let me know for more optimised solution