Private state and automatic store disposal in options stores #2637
-
Recently I encountered a case when I needed a private state in the This works like a charm in // store.js
import { defineStore } from 'pinia';
export const usePrivate = defineStore('auth-private', () => {
const token = null;
return {
token,
};
});
const myStore = defineStore('my-store', {
state: () => ({
name: 'Eduardo',
}),
getters: {
privateStore() {
return usePrivate();
},
},
actions: {
getToken() {
if (this.privateStore.token) {
return this.privateStore.token;
}
return 'no token';
},
},
})();
const TOKEN = myStore.privateStore.token; Here I see two issues:
import myStore from './myStore';
onBeforeUnmount(() => {
myStore.$dispose();
myStore.privateStore.$dispose();
}); This looks a bit funny to me as someone (I mean other components) always should know about the store's private state. I'll be very happy if these issues can be somehow resolved in Of course, this is only a limitation of the I suggest:
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 4 replies
-
FYI: options stores are not the default. You can use both in the same project (mentioned in docs). They cater to different ways of organization, but due to the nature of the setup stores, they will always be more flexible than option stores. In your case, the private store is accessible because you return it in a getter. To keep it private, you need to call |
Beta Was this translation helpful? Give feedback.
You have many ways. The easiest way is to export a function to dispose the store. The plugin approach should also work