How to use provide/inject and pinia stores together? #13313
Unanswered
dha-corey
asked this question in
Help/Questions
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I'm exploring a design using provide/inject to more safely manage "almost-global" values in my application. At the core of it, I'm doing two things:
providein aProvidercomponent that ensure the value is ready to useProvider, and usinginjectto receive said valueIt's working beautifully, with one key exception: pinia stores (and a couple of similar home-brew composables that rely on detached
EffectScopes). As soon as theProvidercomponent unmounts, any components or composables that depend on itsinjected value will also unmount. But a Pinia store won't, so it'll hang on to a potentially stale or invalid value indefinitely.For example, compare these two Pinia Playground examples. In both cases, I intentionally left out the
LanguageProviderif the user chooses'es'as their language.LanguageProvider+useLanguagecomposableWork exactly as expected. If you click
enorfr, the greeting properly renders as "Hello" or "Bonjour". If you clickes, an error is thrown. Regardless of order, you end up in a valid stateLanguageProvider+useLanguageStorepinia storeThe first click works as expected, rendering a greeting for
enandfrand throwing an error fores. However, subsequent clicks fail to change the language. Even though we'reprovide-ing a language offr, our greeting still renders as "Hello".My first thought was to implement a wrapper around
inject()that would detect if it's called from a detachedEffectScopeand return undefined. But I also thinkinjectshould maybe already behave that way, and from other similar threads I've read I get the sense that poking around ingetCurrentScopeandgetCurrentInstanceinternals is not recommended. So I'm curious if there's a better way to handle this, or if there's a reasonably stable way to prevent problematic calls toinjectfrom a store. Or if I've completely misunderstood the intent ofprovide/injectto begin with, and should look elsewhere entirely.Beta Was this translation helpful? Give feedback.
All reactions