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" x-data="{ $store.integer: 0 }">
<button @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.
CodePudding user response:
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>
CodePudding user response:
You have a couple of mistakes in the example code. The corrected version is the following:
<div id="greeting" x-data="{}">
<button @click="$store.integer = 1" x-text="$store.integer ' is the number'"></button>
</div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.store('integer', 0)
})
</script>
- When you create a new variable in the store, the first argument is the name of the variable, the second is its initial value.
- In the component, you don't have to recreate the variable in the
x-dataattribute, since it is defined in thealpine:inithook. So you can use just an emptyx-data(assuming you don't have other variables in the component). - You have a missing
{after=>.
