Skip to content
tech_e edited this page Dec 23, 2025 · 1 revision

State Management with StateTracker

Overview

The StateTracker is Base Framework's global state management system. It provides a centralized store for application-wide state that can be accessed and subscribed to from any component or module. Unlike component-specific states, StateTracker manages state across the entire application.

Core Concepts

State Targets

State Targets are containers for related state values. Each target is identified by a unique ID and can hold multiple state properties (actions).

Actions

Actions are individual state properties within a target. Each action has a value and can have multiple subscribers that are notified when the value changes.

Creating State Targets

Using StateTracker Directly

import { StateTracker } from '@base-framework/base';

// Create or get a state target
const appState = StateTracker.getTarget('app-state');

// Add an action with initial value
appState.addAction('theme', 'light');
appState.addAction('user', null);
appState.addAction('isLoggedIn', false);

Component State Integration

Components automatically create their own state target:

class Page extends Component
{
    setupStates()
    {
        return {
            count: 0,
            name: 'John'
        };
    }

    afterSetup()
    {
        // Access component's state (automatically uses StateTracker)
        this.state.set('count', 10);

        // The component's state is stored in StateTracker
        // with ID: this.id (e.g., 'cp-0')
    }
}

StateTracker Static Methods

getTarget(id)

Get or create a state target by ID:

const appState = StateTracker.getTarget('global-app');

add(targetId, action, state)

Create a target and optionally add an action:

// Create target only
StateTracker.add('user-settings');

// Create target with action
StateTracker.add('user-settings', 'theme', 'dark');

addAction(targetId, action, state)

Add an action to an existing or new target:

StateTracker.addAction('user-settings', 'fontSize', 14);

set(targetId, action, state)

Set the value of an action:

StateTracker.set('user-settings', 'theme', 'light');

getActionState(targetId, action)

Get the current value of an action:

const theme = StateTracker.getActionState('user-settings', 'theme');
console.log(theme); // 'light'

Subscribing to State Changes

on(targetId, action, callBack)

Subscribe to state changes:

const token = StateTracker.on('user-settings', 'theme', (newValue, oldValue) => {
    console.log(`Theme changed from ${oldValue} to ${newValue}`);
    document.body.className = `theme-${newValue}`;
});

off(targetId, action, token)

Unsubscribe from state changes:

StateTracker.off('user-settings', 'theme', token);

remove(targetId, action, token)

Remove a target, action, or subscription:

// Remove specific subscription
StateTracker.remove('user-settings', 'theme', token);

// Remove entire action
StateTracker.remove('user-settings', 'theme');

// Remove entire target
StateTracker.remove('user-settings');

State Target Methods

Once you have a state target, you can use these methods:

Basic Operations

const state = StateTracker.getTarget('app');

// Set value
state.set('user', { name: 'John', age: 30 });

// Get value
const user = state.get('user');

// Increment numeric values
state.set('count', 0);
state.increment('count'); // count = 1
state.increment('count', 5); // count = 6

// Decrement numeric values
state.decrement('count'); // count = 5
state.decrement('count', 3); // count = 2

// Toggle boolean values
state.set('darkMode', false);
state.toggle('darkMode'); // darkMode = true

// Delete an action
state.delete('user');

Batch Updates

// Update multiple actions at once
state.set({
    user: { name: 'Jane' },
    isLoggedIn: true,
    theme: 'dark'
});

Global Store Pattern

Create a centralized store for your application:

import { StateTracker as Store } from '@base-framework/base';

// Create global application store
const AppStore = Store.getTarget('app');

// Initialize application state
AppStore.set({
    user: null,
    isAuthenticated: false,
    theme: 'light',
    notifications: []
});

// Export for use throughout app
export { AppStore };

Usage in components:

import { AppStore } from './store.js';

class Header extends Component
{
    onCreated()
    {
        // Subscribe to store changes
        this.themeToken = AppStore.on('theme', (theme) => {
            this.updateTheme(theme);
        });
    }

    updateTheme(theme)
    {
        this.panel.className = `header theme-${theme}`;
    }

    beforeDestroy()
    {
        // Clean up subscription
        AppStore.off('theme', this.themeToken);
    }

    render()
    {
        return Div({ class: 'header' }, [
            Button({
                text: 'Toggle Theme',
                click: () => {
                    const current = AppStore.get('theme');
                    AppStore.set('theme', current === 'light' ? 'dark' : 'light');
                }
            })
        ]);
    }
}

Using with Directives

State can be accessed in layouts using directives:

class Page extends Component
{
    render()
    {
        return Div([
            // Use onState directive with global state
            Div({
                onState: ['theme', 'app', (theme) => {
                    return theme === 'dark' ? 'Dark Mode' : 'Light Mode';
                }]
            }),

            // Use useState directive to access component state
            Div({
                useState: (state, ele) => {
                    return Span({ text: `Count: ${state.count}` });
                }
            })
        ]);
    }
}

Best Practices

1. Namespace Your Targets

Use clear, hierarchical IDs for state targets:

StateTracker.getTarget('auth');
StateTracker.getTarget('ui-settings');
StateTracker.getTarget('user-preferences');

2. Clean Up Subscriptions

Always unsubscribe in component cleanup:

class Page extends Component
{
    afterSetup()
    {
        this.stateToken = StateTracker.on('app', 'user', this.onUserChange.bind(this));
    }

    beforeDestroy()
    {
        StateTracker.off('app', 'user', this.stateToken);
    }
}

3. Use Component States for Local Data

Don't use global StateTracker for component-specific state:

// ✅ Good - use component state
class Counter extends Component
{
    setupStates()
    {
        return { count: 0 };
    }
}

// ❌ Avoid - unnecessary global state for local data
class Counter extends Component
{
    onCreated()
    {
        StateTracker.add(this.id, 'count', 0);
    }
}

4. Shared State Across Components

Use StateTracker for state that needs to be shared:

// ✅ Good - shared app-wide state
const AuthState = StateTracker.getTarget('auth');
AuthState.set('user', currentUser);
AuthState.set('isLoggedIn', true);

Integration with Component State

Components automatically use StateTracker under the hood. When you use setupStates(), the component creates a StateTracker target with its component ID:

class Page extends Component
{
    setupStates()
    {
        // This creates StateTracker target with ID: this.id (e.g., 'cp-0')
        return {
            count: 0
        };
    }

    afterSetup()
    {
        // Both of these access the same StateTracker target
        this.state.increment('count');
        // Equivalent to:
        // StateTracker.set(this.id, 'count', this.state.get('count') + 1);
    }
}

State Persistence

State values exist for the lifetime of the application. To persist state across page reloads, combine with LocalData:

import { StateTracker, LocalData } from '@base-framework/base';

// Create persistent state
const state = StateTracker.getTarget('app');
const storage = new LocalData({ theme: 'light' });
storage.setKey('app-state');
storage.resume();

// Initialize state from storage
state.set('theme', storage.get('theme'));

// Subscribe to changes and save to storage
state.on('theme', (newTheme) => {
    storage.set('theme', newTheme);
    storage.store();
});

Debugging State

Use the debug directive to inspect state:

{
    useState: (state, ele) => {
        console.log('Current state:', state);
        return Div({ text: JSON.stringify(state) });
    }
}

Or directly access from console:

// In browser console
const state = window.__BASE_STATE__; // if exposed during development

Clone this wiki locally