Alpine.js: Stores

Stores are a state management solution you can use to create a centralized data “storage” for your UI.

To avoid confusion, data stored in a store is not “stored” anywhere. When you reload the page, the store is reinitialized.

But I found stores very useful for one particular thing: accessing a data variable using JavaScript in a clean way.

In my case I had to hide a modal after an htmx HTTP POST request.

Something like this:

document.addEventListener('htmx:afterRequest', (event) => {
  showModal = false
})

But since showModal was defined as x-data="{ showModal: false }" I had no way to access it using JavaScript.

So instead of initializing that variable with x-data, I created a store:

document.addEventListener('alpine:init', () => {
  Alpine.store('mystore', {
    showModal: false,
  })
})

And then I was able to access (and edit) this variable using:

document.addEventListener('htmx:afterRequest', (event) => {
  Alpine.store('mystore').showModal = false
})

Lessons in this unit:

0: Introduction
1: Installing Alpine
2: The basics of Alpine
3: Events
4: Defining data
5: Looping
6: Binding user input to variables
7: Watching variables change
8: ▶︎ Stores