pinia
pinia copied to clipboard
subscriptions are lost during HMR
I have some code like this , it could output correctly when app first loaded or refresh ,but don‘t work after HMR.
const pinia = createPinia();
pinia.use(({ store }) => {
store.$subscribe((mutations, state) => {
console.log('trigger subscritions ', mutations, state);
});
});
I have add some breakpoints in Pinia.js ,and found that subscriptions is emty [] after HMR.
// the "subscriptions" is empty [] after HMR
function triggerSubscriptions(subscriptions, ...args) {
subscriptions.forEach((callback) => {
callback(...args);
});
}
Maybe this can be fixed but it does require some extra logic because any subscription that happens inside a plugin should not be transferred. There could be other cases of subscriptions that should not be transferred to avoid duplication.
Or maybe there is even a better solution within acceptHMRUpdate
@posva what do you mean by "any subscription that happens inside a plugin should not be transferred" here? I'm also running into this problem when trying to develop a plugin locally. The plugin only receives the $subscribe callback once before it is removed. Hot-reloading for plugins seems difficult since the initial plugin registration can have side effects on the current store state (e.g. hydrating the state from localStorage).
Additionally, it looks like this problem goes away when using detached: true by preventing the removeSubscription callback from firing on unmount. Is that configuration expected for plugins that need to subscribe to mutations/actions?
Passing { detached: true } as the second parameter seems to fix this.
thanks
Additionally, it looks like this problem goes away when using
detached: trueby preventing theremoveSubscriptioncallback from firing on unmount. Is that configuration expected for plugins that need to subscribe to mutations/actions?
yes: in most cases you want to use detached: true in plugins so the subscription is never removed
I think it would be very useful to mention it in plugins section of docs, especially in the $subscribe section as if you develop a plugin and use $subscribe or $onAction, you almost certainly want to use detach: true
@F0rsaken Totally! Could you do a PR?
@posva sure, created PR with docs update https://github.com/vuejs/pinia/pull/1781 👍