Chuyển đến nội dung

Bài 8 · Stores and State

Patching and Resetting State

Learn how to change several Pinia state values at once with $patch (object and function forms), replace state with $state, and restore the initial state with $reset.

Setting state one property at a time works, but sometimes you need to change several properties together, replace a list safely, or throw everything away and start over. Pinia provides three tools for that: $patch, $state and $reset. This lesson shows when to use each and what each one costs.

$patch with an object

store.$patch(partialState) merges an object into the state. Only the keys you pass are changed:

JavaScript
const user = useUserStore();

user.$patch({
  name: "Grace",
  settings: { darkMode: true },
});

Nested objects are merged recursively, so the example above changes darkMode but keeps other keys inside settings. Plain object properties are merged, but arrays are replaced as a whole, because merging arrays element by element would be ambiguous.

The benefit over several assignments: all changes are applied as one batch, so DevTools and subscribers see a single mutation instead of three.

$patch with a function

Object patches get awkward for arrays: you cannot say "add an item" or "remove the third item" with a partial object. For that, pass a function. It receives the state and may mutate it freely:

JavaScript
cart.$patch((state) => {
  state.items.push({ sku: "pen", qty: 2 });
  state.total += 4;
  state.lastUpdated = Date.now();
});

This is still one batched mutation. Use the function form when you need push, splice, conditions or calculations.

Compare both forms. The buttons call $patch and the log shows how many subscription events fire (it uses $subscribe, covered in the next lesson, only to count).

$patch with an object and with a function

Look at the event list as you click: each $patch produces one event, while the three assignments produce three. (The subscription uses { flush: "sync" } so that every direct change is reported on its own; by default Pinia batches changes made in the same tick.) The types are "patch object", "patch function" and "direct".

Replacing state with $state

store.$state is the whole state object. Assigning to it patches the store with the new object:

JavaScript
store.$state = { name: "Ada", roles: [] };

This is shorthand for store.$patch(...) with that object. It does not replace the internal object itself, so references to store stay valid. It is useful when you receive a full snapshot from a server or from storage:

JavaScript
const saved = localStorage.getItem("cart");
if (saved) cart.$state = JSON.parse(saved);

(Browser storage is blocked inside the live examples, so this snippet is read-only. We practice persistence in the persistence chapter.)

Replacing an entire pinia's state is also possible, for example when hydrating from a server render: pinia.state.value = serverState. That is an SSR topic.

Resetting with $reset

store.$reset() restores state to what the state() function returns. Pinia calls your function again and patches the result in, which brings back every initial value:

JavaScript
const counter = useCounterStore();
counter.count = 99;
counter.$reset();
console.log(counter.count); // back to the initial value

Typical uses: clear a form after submitting, empty a cart at checkout, wipe data on logout.

$reset and $state

$reset and setup stores

$reset() only exists for stores defined with the options syntax, because Pinia can only rerun an options store's state() function. A setup store has no such function, so calling $reset() on it throws. In a setup store you write your own reset function and return it. Setup stores are the subject of chapter 4.

Which tool when?

Need Use
Change one value store.field = value
Change several values at once, one event store.$patch({ ... })
Add to or remove from arrays, conditional changes in a batch store.$patch((state) => { ... })
Load a whole snapshot store.$state = snapshot
Go back to the beginning (options store) store.$reset()
flowchart TD
    A["Need to change state"] --> B{"How many fields?"}
    B -->|"One"| C["Assign directly"]
    B -->|"Several, simple values"| D["$patch(object)"]
    B -->|"Arrays or logic"| E["$patch(function)"]
    B -->|"Everything"| F{"Back to initial?"}
    F -->|"Yes"| G["$reset()"]
    F -->|"No, new data"| H["$state = snapshot"]

Pick the smallest tool that expresses the change.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What is the main advantage of $patch over several assignments?

    A single batched mutation means subscribers and DevTools see one event instead of many.
  2. 2. How does $patch(object) treat arrays inside the object?

    Plain objects are merged recursively, but arrays are replaced entirely.
  3. 3. When do you need $patch(function)?

    A function can mutate the state freely, which partial objects cannot express.
  4. 4. Where is $reset() available?

    $reset reruns the options store's state() function. Setup stores need a custom reset function.

Summary

  • $patch(object) merges several fields (arrays are replaced) in one batch.
  • $patch(function) lets you mutate the state with array methods and logic, also in one batch.
  • store.$state = obj patches the store with a full snapshot.
  • $reset() restores the state() function's initial values, in options stores only.

Next: Subscribing to State Changes

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.