Skip to content

AlpineJS stores

Frontend

Creating and using AlpineJS stores requires 2 steps: create a store, and use it in components.

Alpine stores in Brush are persistent. They use the Persist Plugin to save data in localStorage. This is the way to go create a stateful application.

  • Edit brush/src/stores/index.ts.
  • Declare a store with init data:
brush/src/stores/index
export type MessagesStore = {
helloWorld: string;
};
export function registerAlpineStores() {
return {
messagesStore: Brush.Persistor.initStore("messagesStore", { helloWorld: "" } as MessagesStore),
// Add stores here
};
}

Example to show two-way data binding and reactivity.

brush/src/components/first-component.ts
export default function () {
Alpine.data("FirstComponent", () => ({}));
}
brush/src/components/second-component.ts
import type { MessagesStore } from "../stores";
export default function () {
Alpine.data("SecondComponent", () => ({
initMessage: "Hello World!",
messagesStore: {} as MessagesStore,
init() {
this.messagesStore = this.$store.messagesStore as MessagesStore;
this.reset();
},
reset() {
this.messagesStore.helloWorld = this.initMessage;
},
}));
}
some-liquid-file.liquid
<div x-data="FirstComponent()"><span x-text="$store.messagesStore.helloWorld"></span></div>
<div x-data="SecondComponent()">
<input type="text" x-model="$store.messagesStore.helloWorld">
<button type="button" @click="reset">Reset message</button>
</div>