pinia icon indicating copy to clipboard operation
pinia copied to clipboard

subscriptions are lost during HMR

Open duoyue opened this issue 3 years ago • 9 comments

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);
    });
}

duoyue avatar Jan 25 '22 10:01 duoyue

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 avatar Jan 27 '22 10:01 posva

@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).

davidmyersdev avatar Jun 05 '22 20:06 davidmyersdev

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?

davidmyersdev avatar Jun 05 '22 20:06 davidmyersdev

Passing { detached: true } as the second parameter seems to fix this.

Alanscut avatar Jul 19 '22 12:07 Alanscut

thanks

tansan-dev avatar Aug 25 '22 03:08 tansan-dev

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?

yes: in most cases you want to use detached: true in plugins so the subscription is never removed

posva avatar Oct 03 '22 10:10 posva

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 avatar Oct 31 '22 12:10 F0rsaken

@F0rsaken Totally! Could you do a PR?

posva avatar Nov 07 '22 07:11 posva

@posva sure, created PR with docs update https://github.com/vuejs/pinia/pull/1781 👍

F0rsaken avatar Nov 07 '22 13:11 F0rsaken