4

To initialize a store I have

document.addEventListener('alpine:init', () => {
  Alpine.store('selectedInput', 0)
})

But when I do this in a function further down, it doesn't update selectedInput:

function example() {
  Alpine.store('selectedInput', 3)
}
eskimo
  • 2,421
  • 5
  • 45
  • 81

1 Answers1

4

Using an example from the documentation website - https://alpinejs.dev/globals/alpine-store

Alpine.store('darkMode', {
    on: false,

    toggle() {
        this.on = ! this.on
    }
})

darkMode is the name of your store. on is a property toggle is a function

So in your case, it should look something like this -

Alpine.store('nameOfStore', {
    selectedInput: 0,

    example() {
        this.selectedInput = 3
    }
})

You can replace nameOfStore with anything you like.

To call the function, you will do this - $store.nameOfStore.example()

davexpression
  • 117
  • 1
  • 8
  • Yep that's in the docs. At the bottom of that page there's also `Alpine.store('darkMode', false)`, so you can set a value directly it seems. As per my post this actually works on initialization, just not further down in the file when I want to use that line to set the variable to a different value. – eskimo Jul 03 '21 at 14:26
  • @eskimo ok... inside example() do this `this.$store.selectedInput = 3` – davexpression Jul 06 '21 at 09:32