๐Ÿ›’ Shared state

A SharedState holds one object. Components read it, update it, and re-render when it changes.

A tiny shop

These buttons are a component that updates the cart state. Everything else on the page that subscribes to it reacts on its own.

Shared state

A SharedState holds one object that several components read and update. Every change notifies the subscribers, so the badge below re-renders by itself when the product buttons above add to the cart.

Subscriber

Current state

How to use it

  1. Create the state once with its initial value and share it (a module export, or dispatcher.createState('cart', โ€ฆ) to get its changes in the log).

    // shared.ts
    import { SharedState } from 'html-scoped-component-importer';
    
    export const cartState = new SharedState({ items: [] as Product[] });
  2. Update with set(): pass the changed keys, or a function of the current state. Changes are shallow-merged and the state is frozen, so never mutate it directly.

    // components/ProductList.ts
    cartState.set(current => ({ items: [...current.items, product] }));
    
    // anywhere
    cartState.set({ items: [] });
  3. Read and subscribe: get() returns the current value, subscribe() calls you with the next and previous state and returns an unsubscribe function for _destroy().

    // components/CartBadge.ts
    const render = () => {
      element.textContent = `๐Ÿ›’ ${cartState.get().items.length} item(s)`;
    };
    render();
    this.unsubscribe = cartState.subscribe(render);

Several subscribers, previous and next state

Three components subscribe to the same moodState. The last one uses the previous state passed to subscribers to show what changed.

export const moodState = new SharedState({ mood: 'happy' });

// components/MoodDiff.ts
moodState.subscribe((next, previous) => {
  element.textContent = `${previous.mood} โ†’ ${next.mood}`;
});