Radiant0.11.0

Zustand store

The cart lives in Zustand (or a store with the same getState / setState / subscribe surface). Checkout, analytics, or a React island already call setState. A Radiant badge on the header should patch the count without copying snapshots into @state.

In the bag: 1

  • Mug

Add mug and Add lamp write the store. The badge binds this.$.count. The list reads this.items in render() because the row structure changed.

The store

In an app, install Zustand and pass the store createStore() from zustand/vanilla returns. That object is already getState, setState, and subscribe, and the vanilla entry does not import React.

import { createStore } from 'zustand/vanilla';
 
type CartState = {
	items: string[];
};
 
export const cartStore = createStore<CartState>(() => ({
	items: ['Mug'],
}));
 
export function addCartItem(name: string): void {
	cartStore.setState({ items: [...cartStore.getState().items, name] });
}

When a React island already owns the store through create() from zustand, pass that hook object to @fromStore as it is, not useCartStore(): it carries the same getState and subscribe.

The live demo uses a store with that same surface so the docs app does not depend on Zustand.

The hosts

import { RadiantElement, customElement, fromStore } from '@ecopages/radiant';
import { addCartItem, cartStore } from './cart-store';
 
@customElement('cart-badge')
class CartBadge extends RadiantElement<{ count: number }> {
	@fromStore(cartStore, (state) => state.items.length)
	count!: number;
 
	override render() {
		return <span>{this.$.count}</span>;
	}
}
 
@customElement('cart-list')
class CartList extends RadiantElement<{ items: string[] }> {
	@fromStore(cartStore, (state) => state.items)
	items!: string[];
 
	override render() {
		return (
			<ul>
				{this.items.map((item) => (
					<li>{item}</li>
				))}
			</ul>
		);
	}
}

A selector that returns state.items.length stays quiet when something else in the store changes. A selector that returns a new array from filter updates on every store change.

Do not write this.count = 2. Assignment throws. Call cartStore.setState or an action on the store.

See Also