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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!