Using Stores
Edit this pageThe stores API are available at solid-js/stores. They allow the creation of stores: proxy objects that allow a tree of signals to be independently tracked and modified.
createStore
The create function takes an initial state, wraps it in a store, and returns a readonly proxy object and a setter function.
As proxies, store objects only track when a property is accessed.
When nested objects are accessed, stores will produce nested store objects, and this applies all the way down the tree.
However, this only applies to arrays and plain objects. Classes are not wrapped, so objects like Date
, HTMLElement
, RegExp
, Map
, Set
won't be granularly reactive as properties on a store.
Getters
Store objects support the use of getters to store calculated values.
These are getters that rerun when accessed, so you still need to use a memo if you want to cache a value:
Arrays in Stores
As of version 1.4.0, the top level state object can be an array. In prior versions, you need to create an object to wrap the array:
Modifying an array inside a store will not trigger computations that subscribe to the array directly. For example:
However, subscribing to any signals that change inside the array will trigger those computations.
Updating Stores
Changes can take the form of function that passes previous state and returns new state or a value. Objects are always shallowly merged. Set values to undefined to delete them from the Store.
To delete all properties of an object, you can use reconcile like so:
It supports paths including key arrays, object ranges, and filter functions.
setState also supports nested setting where you can indicate the path to the change. When nested the state you are updating may be other non Object values. Objects are still merged but other values (including Arrays) are replaced.
Path can be a string of keys, array of keys, iterating objects (from, to), or filter functions. This gives incredible expressive power to describe state changes.