Store Utilities

modifyMutable

Edit this page

modifyMutable streamlines the process of making multiple changes to a mutable Store, as obtained through the use of createMutable.

It operates within a single batch, ensuring that dependent computations are updated just once, rather than triggering updates for each individual change.

import { modifyMutable } from "solid-js/store"
function modifyMutable<T>(mutable: T, modifier: (state: T) => T): void

The function takes two arguments:

  1. The first argument is the mutable Store that needs modification.
  2. The second argument is a Store modifier, which could be one of those returned by reconcile.

For example, if the UI depends on multiple fields of a mutable:

import { createMutable } from "solid-js/store"
const state = createMutable({
user: {
firstName: "John",
lastName: "Smith",
},
});
<h1>Hello {state.user.firstName + " " + state.user.lastName}</h1>;

Modifying n fields in sequence will cause the UI to update n times:

state.user.firstName = "Jane";
state.user.lastName = "Doe";

To trigger just a single update, the fields can be modified using a batch:

import { batch } from "solid-js"
batch(() => {
state.user.firstName = "Jane";
state.user.lastName = "Doe";
});

modifyMutable combined with reconcile or produce provides two alternate ways to do similar things:

import { modifyMutable, reconcile } from "solid-js/store"
// Replace state.user with the specified object (deleting any other fields)
modifyMutable(
state.user,
reconcile({
firstName: "Jane",
lastName: "Doe",
})
);
import { modifyMutable, produce } from "solid-js/store"
// Modify two fields in batch, triggering just one update
modifyMutable(
state,
produce((state) => {
state.user.firstName = "Jane";
state.user.lastName = "Doe";
})
);
Report an issue with this page