-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Closed
Description
What problem is this solving
Sometimes we need to define stores dynamically - e.g. to be able to use 2 instances of the same store that don't share the same state.
In such a case, in Vuex, I create a factory function that takes dependencies and return an initialized instance of a Vuex store. Then, when I no longer need that store I can call unregisterModule()
and destroy that store.
In Pinia I didn't find such an option.
Proposed solution
<script>
import createMyStore from '@/store/createMyStore';
import { onUnmounted } from '@vue/composition-api';
export default {
name: 'App',
setup() {
const useStore = createMyStore({
id: 'myId',
useSettings: () => ({
value: 1,
})
});
const { combinedValue, $destroy } = useStore();
onUnmounted(() => {
$destroy();
})
return {
combinedValue,
}
},
}
</script>
import { defineStore } from 'pinia'
export default ({ useSettings, id }) => {
const mainId = 'myStore'
return defineStore({
id: `${mainId}_${id}`,
state: () => ({
value: 1,
}),
getters: {
combinedValue() {
const settings = useSettings();
return this.value + settings.value;
},
},
})
}
Describe alternatives you've considered
I don't think there's any alternative. We can call $reset()
to restore the state - this will free-up the memory, but it won't destroy the instance entirely.
saleh-gholamian, hosseinjarrahi and mrpwes