Global Store - cynchro/OldSchoolFrontFrame GitHub Wiki

Global Store

The global store is shared reactive state that persists across module navigation. Use it when two or more modules need access to the same data.


Initial store state

Define the initial store state in initApp():

initApp({
  routes: { ... },
  store: {
    currentUser: null,
    notifications: [],
    theme: 'light',
  },
});

Accessing the store

The store is available in every module via ctx.store:

defineModule({
  methods: {
    login(ctx) {
      ctx.store.state.currentUser = { name: 'Alice', role: 'admin' };
    },
    logout(ctx) {
      ctx.store.state.currentUser = null;
    },
    addNotification(ctx, message) {
      ctx.store.state.notifications.push({ message, id: Date.now() });
    },
  },
});

Like module state, the store is a Proxy — mutations are tracked automatically.


Binding store state in templates

Use the store. prefix in any data-bind or data-model attribute:

<!-- Read store value -->
<span data-bind="store.currentUser.name"></span>

<!-- Two-way bind to store -->
<input data-model="store.filters.query" />

<!-- Conditional display (via method + manual DOM) -->
<div id="user-menu"></div>

Store API

ctx.store.state

The reactive state object. Mutate it directly:

ctx.store.state.theme = 'dark';
ctx.store.state.currentUser = null;

ctx.store.getState()

Returns the full current state snapshot (non-reactive copy):

const snap = ctx.store.getState();
console.log(snap.currentUser);

ctx.store.setState(path, value)

Set a value at a dot-notation path:

ctx.store.setState('currentUser.name', 'Bob');
ctx.store.setState('filters.active', true);

ctx.store.patchState(partial)

Merge a partial object into the top-level state:

ctx.store.patchState({
  theme: 'dark',
  currentUser: { name: 'Alice' },
});

ctx.store.subscribe(listener)

Subscribe to all store changes:

ctx.store.subscribe((path, value) => {
  console.log(`store.${path} changed to`, value);
});

ctx.store.subscribePath(path, fn)

Subscribe to a specific path only:

ctx.store.subscribePath('currentUser', (value) => {
  console.log('User changed:', value);
});

Accessing the store outside a module

initApp() returns a reference:

const app = initApp({ ... });

const store = app.getStore();
store.state.notifications = [];

When to use the store vs module state

Use case Use
Data only needed in one module ctx.state
Authenticated user info ctx.store.state
Global filters or search query ctx.store.state
Navigation or UI state shared between modules ctx.store.state
API response only used in one view ctx.state

Rule of thumb: start with module state. Promote to store only when a second module needs the same data.

⚠️ **GitHub.com Fallback** ⚠️