Store Mutations — SolidJS

A store can't be changed directly (state.items.push(4) has no effect, the development console prints Cannot mutate a Store directly). setState(produce(s => {…

shop.cart.push("The Rainbow Troops") looks reasonable, and on a plain array it works. On a Solid store, that line changes nothing, because a store can only be changed through its setter. A change that takes more than one step gets long when every step is written as its own setter call.

For that, "solid-js/store" has two helpers. produce lets you write changes as if you were editing a plain object, then applies them all at once. reconcile puts new data from a server in place without throwing away objects that are still the same. Think of Nadia and the shelf staff. If every correction is shouted one at a time, the shelf staff tidy the shelf after every shout. produce is writing all the corrections on one note and handing it over once. Then every morning the supplier sends a new catalogue. Nadia doesn't throw out every card and print them again. She matches the new catalogue against the cards she has by book code, and only changes the numbers that differ. That's reconcile.

A store is read from anywhere, changed through its setter

const [state, setState] = createStore({ items: [1, 2, 3] })
state.items.push(4)

This adds nothing: state.items stays [1, 2, 3]. A store is read-only outside its setter, so the push above fails with no error, and in development mode the console prints Cannot mutate a Store directly twice (once for items[3], once for length). The right way: through setState, or produce inside it.

produce: write it like a plain object

import { createStore, produce } from "solid-js/store"

function App() {
  const [state, setState] = createStore({ items: ["A", "B"] })

  const addItem = () => {
    setState(produce(s => {
      s.items.push("C")
    }))
  }

  return (
    <div>
      <p>Items: {state.items.join(", ")}</p>
      <button onClick={addItem}>Add</button>
    </div>
  )
}
Event state.items Paragraph
Page opens ["A", "B"] Items: A, B
Click Add ["A", "B", "C"] Items: A, B, C

One click, how many updates

Nadia's Bookshop with the cart in a store and a summary effect:

createEffect(() => {
  console.log("summary:", shop.books[0].stock, "stock,", shop.cart.length, "in cart")
})

// Version A: two setters
const order = () => {
  setShop("books", 0, "stock", s => s - 1)
  setShop("cart", c => [...c, shop.books[0].title])
}

// Version B: one produce
const order = () => {
  setShop(produce(t => {
    t.books[0].stock -= 1
    t.cart.push(t.books[0].title)
  }))
}

Version A calls setShop twice in one click. If you come from React, you might expect the two to be merged into one update. Take a guess: how many summary lines does one click on version A print, 1 or 2?

Tested in Solid 1.9, clicking Order The Rainbow Troops once:

Version Console
A, two setShop summary: 3 stock, 0 in cart, then summary: 3 stock, 1 in cart
B, one produce summary: 3 stock, 1 in cart

Two setters, two updates. Solid 1.9 doesn't gather the setters inside a click handler: each setShop immediately runs everything that reads that part. Between the two there's a half-done state, the stock already down but the cart not yet longer, and the effect gets to see it. produce applies all its changes in one update. For several separate setters, signals included, wrap them in batch from "solid-js": batch(() => { setShop(...); setShop(...) }) also prints just one line.

reconcile: new data, old objects

A new catalogue from the server: The Rainbow Troops still 4, This Earth of Mankind now 5, Beauty Is a Wound now 3, plus The Dancer. Each book has an id. There are two ways to put it in place:

import { reconcile } from "solid-js/store"

setShop("books", fetchCatalog())             // replace
setShop("books", reconcile(fetchCatalog()))  // match

With a gift note on the card for The Rainbow Troops, tested in Solid 1.9:

replace reconcile
Rows made 4, every card made again 1, only The Dancer
Texts replaced all of them, through new rows 3, only the stocks that changed
The gift note gone stays

⚠️ A produce that does nothing, and cards rebuilt for no reason

TL;DR: A store can't be changed directly (state.items.push(4) has no effect, the development console prints Cannot mutate a Store directly). setState(produce(s => { s.items.push("C") })) lets you write changes like a plain object, then applies them in one update. Two setShop in a row in a click handler means two updates, with a half-done state between them; produce or batch makes it one. setShop("books", reconcile(newData)) puts server data in place by matching id: the same objects are kept, only what differs is replaced, so the rows and what's in them stay.

⚡ A store changes only through its setter

Guess first: const [state, setState] = createStore({ items: [1, 2, 3] }) then state.items.push(4). What does state.items hold?

Still [1, 2, 3], with no error. In development mode, the console prints Cannot mutate a Store directly.

Meaning: A store can be read from anywhere, but it can only be changed through its setter.

⚡ produce: write it like a plain object

Write:

const addItem = () => {
  setState(produce(s => {
    s.items.push("C")
  }))
}

Meaning: Inside produce, s may be changed like a plain object. The function must be passed to the setter: produce(...) on its own changes nothing.

⚡ One update, not two

Meaning: Two setShop calls in a row in one click mean two updates, with a half-done state between them. produce applies all its changes in one update, and batch from "solid-js" joins several separate setters.

⚡ reconcile: new data, old objects

Write:

setShop("books", reconcile(fetchCatalog()))

Meaning: reconcile matches the new data against the store's contents by id. The same item stays the same object, so its row isn't made again and the gift note in it stays.

What you will learn