Home > Back-end >  Storing an integer variable in local storage in alpine.js
Storing an integer variable in local storage in alpine.js

Time:01-16

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>
  1. When you create a new variable in the store, the first argument is the name of the variable, the second is its initial value.
  2. In the component, you don't have to recreate the variable in the 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).
  3. You have a missing { after =>.
  •  Tags:  
  • Related