Cami provides a store utility to manage shared state across multiple components. A store consists of a state object, actions for modifying that state, and memos for computing derived values.
To use a store:
- Create the store: Use
store({ name: 'StoreName', state: { ... } }). - Define Actions: Use
store.defineAction(name, handler) to mutate state. The handler receives { state, payload }. - Define Memos: Use
store.defineMemo(name, selector) to create derived state. The selector receives { state }. - Read State: In a component's
template(), call store.getState() to access the current state. - Access Memos: Use
store.memo(name) to retrieve a computed value. - Dispatch Actions: Use
store.dispatch(name, payload) to trigger state changes.
import { store, html, ReactiveElement } from 'cami';
// 1. Create the store
const CartStore = store({
name: "CartStore",
state: { cartItems: [] },
});
// 2. Define actions
CartStore.defineAction("add", ({ state, payload }) => {
state.cartItems.push({ ...payload, cartItemId: Date.now().toString() });
});
// 3. Define memos
CartStore.defineMemo("cartTotal", ({ state }) => {
return state.cartItems.reduce((acc, item) => acc + item.price, 0);
});
// 4. Use in a component
class CartElement extends ReactiveElement {
template() {
const { cartItems } = CartStore.getState(); // Read state
const total = CartStore.memo("cartTotal"); // Read memo
return html`
<div>
<p>Total: $${total}</p>
<button @click=${() => CartStore.dispatch("remove", { id: 1 })}>Remove</button>
</div>
`;
}
}