feat(hmr): extend acceptHMRUpdate
to allow for cleaning up side effects of existing store
#2793
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Changes
This PR adds to possibility of passing a cleanup function as an optional third argument to
acceptHMRUpdate
. This cleanup function can be used to clean up side effects of the existing store before initializing the new store. This is useful if you have event listeners or other side effects that need to be cleaned up in the old store.This solves a non-trivial case. Usually, having side effects inside a Pinia store is probably not such a great idea. However, it happens, and if it does, we need to provide a way to make sure those side effects can be properly cleaned up during HMR.
Let's say you have an app that relies on a lot of event listeners, and you want to manage them centrally and close to some global state. If there isn't an obvious Vue component to add and remove all these event listeners, you might choose to manage these event listeners in a Pinia store. While working on this Pinia store, you might need to clean up some of those event listeners, before HMR replaces the existing store with the new one. We can use
onScopeDispose
to run some code when the store is disposed, but nothing is disposed when HMR swaps the stores, so we can't use that mechanism here. For better control over HMR, we need a way to talk to the existing store, just before it gets replaced. This PR provides that mechanism.To do
/scroll-store
route).onBeforeHMRReplace
hook being a viable alternative. A user would need to callonBeforeHMRReplace
in a setup store, just like withonScopeDispose
. It would probably require us to detect and register any calledonBeforeHMRReplace
hooks during the setup phase (store initialization) and manually trigger their callbacks inacceptHMRUpdate
.Example (taken from the modified docs)