I wanted to store an integer value in local storage using alpine.js
There is a button that increments the value by 1 when pressed.
Here is how I thought it should be:
<div id="greeting" class="inner" x-data="{ $store.integer: 0 }">
<button class="button bouncy" @click="$store.integer+=1" x-text="$store.integer + ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () =>
Alpine.store('store', integer)
})
</script>
This didn't work. I tried some other implementations, but none of them seemed to work. I also tried not adding the $store, since it showed the integer as "undefined" when I did that.
Alpine has the persist plugin which looks like it might suit your needs.
https://alpinejs.dev/plugins/persist
<div x-data="{ count: $persist(0) }">
<button x-on:click="count++">Increment</button>
<span x-text="count"></span>
</div>
You have a couple of mistakes in the example code. The corrected version is the following:
<div id="greeting" class="inner" x-data="{}">
<button class="button bouncy" @click="$store.integer += 1" x-text="$store.integer + ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('integer', 0)
})
</script>
x-data attribute, since it is defined in the alpine:init hook. So you can use just an empty x-data (assuming you don't have other variables in the component).{ after =>.