Skip to content

Store

Deep reactive state for nested objects and arrays.

Create a store

A store wraps an object. Reads through .state are tracked down to each property, so a binding updates only when the property it reads changes.

const cart = store({
  items: [] as { id: number; name: string; qty: number }[],
  coupon: '',
});

cart.state.items.length; // tracked

Write with set()

set() takes a path and a value. A function as the last argument receives the previous value.

cart.set('coupon', 'SPRING');
cart.set('items', (items) => [...items, { id: 1, name: 'Tea', qty: 1 }]);
cart.set('items', 0, 'qty', (qty) => qty + 1);

merge(partial) sets several top level keys, update(fn) replaces the whole state, and unwrap() returns a plain copy.

Example

produce()

produce() lets you write a change as a mutation of a draft.

cart.set('items', produce((items) => {
  items.push({ id: 3, name: 'Jam', qty: 1 });
}));