Alpine with Spruce : ReferenceError: $store is not defined

Viewed 1711

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/spruce@2.x.x/dist/spruce.umd.js", [], '2.6.3');

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

Which translates to

<script type='text/javascript' src='https://cdn.jsdelivr.net/gh/ryangjchandler/spruce@2.x.x/dist/spruce.umd.js?ver=2.6.3' id='spruce-js'></script>
<script type='text/javascript' src='https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/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.

0 Answers
Related