Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

115
Views
Storing an integer variable in local storage in alpine.js

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report

0

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>
  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 =>.
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!