produce
Edit this pagenote
In Solid 2.0, the produce-style draft mutation is now the default behavior of the createStore setter. You no longer need to wrap your setter callback in produce -- simply mutate the draft directly inside the setter.
produce is an Immer inspired API for Solid's Store objects that allows the store to be mutated using a draft pattern.
import { produce } from "solid-js/store"import type { NotWrappable, Store } from "solid-js/store"
function produce<T>( fn: (state: T) => void): ( state: T extends NotWrappable ? T : Store<T>) => T extends NotWrappable ? T : Store<T>;Default Setter in Solid 2.0
In Solid 2.0, the store setter already receives a mutable draft. The following two patterns are equivalent:
import { createStore, produce } from "solid-js/store";
const [state, setState] = createStore({ user: { name: "John", age: 30, }, list: ["book", "pen"],});
// Solid 2.0: draft-first setter (preferred -- no produce wrapper needed)setState((draft) => { draft.user.name = "Jane"; draft.list.push("pencil");});
// Equivalent using explicit produce (still works, but redundant for setStore)setState( produce((state) => { state.user.name = "Jane"; state.list.push("pencil"); }));Standalone Use
The produce utility is still useful when you need to create a reusable modifier function outside of setStore, or when working with other APIs that accept store modifiers:
import { produce } from "solid-js/store";
// Create a reusable modifierconst addItem = (item: string) => produce((state) => { state.list.push(item); });
// Apply it latersetState(addItem("pencil"));