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
-
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:
provide
in aProvider
component that ensure the value is ready to useProvider
, and usinginject
to receive said valueIt's working beautifully, with one key exception: pinia stores (and a couple of similar home-brew composables that rely on detached
EffectScope
s). As soon as theProvider
component unmounts, any components or composables that depend on itsinject
ed 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
LanguageProvider
if the user chooses'es'
as their language.LanguageProvider
+useLanguage
composableWork exactly as expected. If you click
en
orfr
, 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
+useLanguageStore
pinia storeThe first click works as expected, rendering a greeting for
en
andfr
and 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 detachedEffectScope
and return undefined. But I also thinkinject
should maybe already behave that way, and from other similar threads I've read I get the sense that poking around ingetCurrentScope
andgetCurrentInstance
internals 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 toinject
from a store. Or if I've completely misunderstood the intent ofprovide
/inject
to begin with, and should look elsewhere entirely.Beta Was this translation helpful? Give feedback.
All reactions