Initialize state with calling an action that makes an API call #1176
-
My use case is storing all available languages. So my store looks like:
The problem is, when I need to use this store on a component I should do:
Calling the I can fix the multiple API calls updating the loadFromApi actions with:
but I don't quite like the solution, I have to keep calling the Is there no hook to initialize? Something like this would be nice:
Or is there another way?
And the store has the logic to initialize himself doing the |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 8 replies
-
@mpont91 I am trying to have a wrapper as a solution, any place using const xx = useDemoStore() won't need to change. all usage will be the same as normal store export const useDemoStore = () => {
const innerStore = defineStore({
id: "demo",
state: () => ({
counter: 0,
}),
actions: {
asyncList() {
console.info("asyncList");
setTimeout(() => {
this.counter = 100;
}, 1000);
},
},
});
const s = innerStore();
if (s.counter == 0) {
s.asyncList();
}
return s;
}; |
Beta Was this translation helpful? Give feedback.
-
@dreambo8563 when I do this, I get a type error in my computer mapState and mapActions functions;
Error: |
Beta Was this translation helpful? Give feedback.
-
some related discussion here about adding more hooks to stores - with ideally the functionality to know when the store is no longer being used... |
Beta Was this translation helpful? Give feedback.
@mpont91 I am trying to have a wrapper as a solution, any place using const xx = useDemoStore() won't need to change. all usage will be the same as normal store