Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alpine with Spruce : ReferenceError: $store is not defined

I am getting an error

ReferenceError: $store is not defined

I am using alpine and spruce in my wordpress theme and they are loaded as follows.

wp_enqueue_script('spruce', "https://cdn.jsdelivr.net/gh/ryangjchandler/[email protected]/dist/spruce.umd.js", [], '2.6.3');

wp_enqueue_script('alpineJs', "https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js", [], '2.8.1');

Which translates to

<script type='text/javascript' src='https://cdn.jsdelivr.net/gh/ryangjchandler/[email protected]/dist/spruce.umd.js?ver=2.6.3' id='spruce-js'></script>
<script type='text/javascript' src='https://cdn.jsdelivr.net/gh/alpinejs/[email protected]/dist/alpine.min.js?ver=2.8.1' id='alpineJs-js'></script>

I found this issue in https://github.com/ryangjchandler/spruce/issues/41, and I believe I am doing the same thing which is adviced here.

But when I try to dump.

console.log($store)

I am getting $store not defined. The reason I am trying to define it here is because alpine is throwing this error.

Alpine Error: "TypeError: Cannot read property 'product' of undefined"

Expression: " product = $store.application.product"
Element: <div x-data=​"{product:​ '1'}​" @productchange.window=​"product = $event.detail.product" x-init=​" product = $store.application.product">​…​</div>​

This is how I am calling Spruce in my bundled JS.

 window.Spruce.store('application', {
   product: getProduct(),
 })

Earlier I was calling spruce without window using spruce v-0.6.1 and alpine v-2.3.5 which was working fine. But today I am getting this error.

UPDATE

I am able to access product value in JS like this.

console.log(Spruce.store('application').product)

I have also deduced that if, I switch

x-init="product = $store.application.product"

this to

x-init="$nextTick( () => {
     product = $store.application.product
  })"

everything works but the issue is I am now unable to set the initial state.

I am not getting the value of $store.application.product at the website load.

like image 854
bhanu Avatar asked Feb 18 '26 16:02

bhanu


1 Answers

After looking into this for about an hour. I searched the alpine for "alpine store" to see if there are alternatives and I think that there may be some conflicts or they have rolled Spruce into Alpine which may be why Spruce is now in public archive.

That said for all the lost souls out there. Here is the link to the Alpine.store() documentation.

https://alpinejs.dev/globals/alpine-store

like image 74
AvidDabbler Avatar answered Feb 20 '26 06:02

AvidDabbler