How to dynamically decide which imported store i have to use from another store? #2586
-
Hi, let's imagine i have a main store that is using another two stores. In this main store i have a function that receive some parameters, and depending of one of them (type) I have to use the corresponding imported store.
Then, if i have in my component: I want then call: I could add a switch, and depending of type value, call articleWebcamStore.addNewItem() or useArticleLaptopStore.addNewItem()... but i would like to do it in a more generic way (perhaps in the future i have to use another 10 stores). Is there any way of dynamically generate the reference to the right store every time I use addItem ? Thanks. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
If addItem function can be asynchronous, you can import the stores dynamically using template literal: https://stackblitz.com/edit/vitejs-vite-7jamvv?file=src%2Fstores%2Fmain.store.js Otherwise: const stores = {
WEBCAM: useArticleWebcamStore,
LAPTOP: useArticleLaptopStore,
// Add more
}
function addItem(type, name) {
const store = stores[type]()
store.addNewItem(name)
} Wish you lots of health, peace, and success. 👋🔥💚 |
Beta Was this translation helpful? Give feedback.
If addItem function can be asynchronous, you can import the stores dynamically using template literal:
https://stackblitz.com/edit/vitejs-vite-7jamvv?file=src%2Fstores%2Fmain.store.js
Otherwise:
Wish you lots of health, peace, and success. 👋🔥💚