Updating State and Reactivity Details
🎯 Introduction
By the end of this article, you will know three ways to update Pinia state and when to use each. You will also learn about reactivity pitfalls when working with objects and arrays to make state management more reliable.
✨ Direct Updates: The Simplest Approach
Pinia allows direct state updates, one of its biggest differences from Vuex.
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
});
In a component:
<template>
<p>{{ counter.count }}</p>
<button @click="counter.count++">Add 1</button>
<button @click="counter.count = 0">Reset</button>
</template>
$patch or an action.🛠 $patch: Updating Multiple Properties
Use $patch to make updates to several state properties clearer:
counter.$patch({
count: 10,
name: 'Taylor',
});
$patch also accepts a function, which is useful when updates depend on the current state:
counter.$patch((state) => {
state.count++;
});
$patch receives the current state as its argument, allowing you to modify it directly. This keeps related logic together and makes changes easier to track.🔄 $reset: Restoring Initial Values
Call $reset to restore the initial values defined in the state() function:
counter.$reset(); // count returns to 0
$reset only applies to the initial state defined through state: () => ({}). If you previously replaced an entire object property with $patch, the reset behavior may differ from what you expect.⚡ Reactivity Pitfalls with Objects and Arrays
Replacing an Entire Object
The following approach breaks reactivity:
const user = useUserStore();
user.info = { name: 'Taylor', age: 25 }; // ❌ May lose reactivity
Why? Replacing the entire info reference can interfere with Pinia’s reactive tracking of that property.
The recommended approach:
// ✅ Update individual properties
user.info.name = 'Taylor';
user.info.age = 25;
// ✅ Or use $patch
user.$patch({
info: { name: 'Taylor', age: 25 },
});
Array Operations
Array methods such as push and splice preserve reactivity:
const list = useListStore();
list.items.push('New item'); // ✅
list.items.splice(0, 1); // ✅
Be careful when replacing an entire object through an array index:
list.items[0] = { id: 2, name: 'New' }; // ⚠️ May not trigger an update
A safer approach:
list.$patch((state) => {
state.items[0] = { id: 2, name: 'New' };
});
$patch.💡 Choosing Between Three Update Approaches
| Approach | When to use it | Example |
|---|---|---|
| Direct updates | Simple assignment to a single property | counter.count++ |
$patch | Batch updates or complex object/array operations | counter.$patch({...}) |
| Actions | Complex or reusable business logic | counter.add() |
❓ Questions and Answers
Q1: Are direct updates or $patch better?
Neither is always better. Direct updates are more concise for one property; $patch is clearer for multiple properties or complex operations.
Q2: Can $reset reset state changed by an action?
Yes. $reset restores the initial values returned by state(), regardless of how they were changed.
Q3: Why does replacing an entire object lose reactivity?
The reactivity system tracks object references. Replacing a reference with a new plain object disconnects the original reactive proxy.
Q4: Does assigning an array element by index always fail?
Not always, but its behavior is less reliable than push/splice/$patch. Prefer the safer approaches to avoid pitfalls.
🧪 Exercise
Complete the following usePointStore with:
- A
pointsproperty initialized to0. - An
add(n)action that increasespointsbyn. - A
consume(n)action that spends points only when enough points are available. - A
reset()action that resets points to0.
import { defineStore } from 'pinia';
export const usePointStore = defineStore('point', {
state: () => ({
points: 0,
}),
actions: {
// Write your code here
},
});
🎉 You now know the different ways to update state! Next, we will handle asynchronous requests in actions.
