Using $store
with x-data
#4088
Replies: 2 comments 11 replies
-
There is absolutely no reason to do such a thing. X-data is for local components that have their own state. Store is for globally shared data. |
Beta Was this translation helpful? Give feedback.
-
A better error message and a mention in the documentation is probably the right path. You can't really use a $store in x-data in that way. If you put it as a root object, as you saw, alpine tries to inject the magic twice, leading to an error. If it didn't error, magic like $el and $root would be wrong because they would point to the wrong html element in one of the 2 components. Using it for one component works by chance but it may lead to unexpected behaviors if you start using the store sub properties somewhere else. If you put it in a property, it's even more worst. One may think that it works but in reality you are reassigning the property of the single component, non the global store so the component won't stay in sync. In this case, you either get something you didn't expect or, if that what you wanted to achieve, you should have use alpine.data. See https://codepen.io/SimoTod/pen/WNWwKep |
Beta Was this translation helpful? Give feedback.
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 found myself in a situation where I wanted to reuse much of a navigation component on two different places in the HTML document and thought I could just do
x-data="$store.navigation"
to access thenavigation
store's properties both places. That, however, lead to the error described in #1940:Using
x-data="$store.navigation"
worked when there was only one occurrence of it, but when I added the second, the above error started appearing. I ended up removingx-data
in both places and referencing$store.navigation.*
everywhere I needed to access one of its properties or methods.My takeaway here is that it would be nice if Alpine would either:
$store
withx-data
more than once.Beta Was this translation helpful? Give feedback.
All reactions