Getters and actions
A store holds state, but state alone is not enough. You need values derived from it, and you need ways to change it. Pinia splits those jobs: getters derive, actions mutate.
A getter is like computed. It takes state, returns a value, and caches the
result until a dependency changes. It takes no arguments and should have no side
effects:
getters: {
total: (state) => state.items.reduce((sum, item) => sum + item.price, 0),
},
An action is like a method. It changes state, can call other actions, and can be
async — the place for side effects such as fetching. Inside an action, this
is the store:
actions: {
async load() {
this.items = await fetchItems();
},
},
So the split is a rule about responsibility. If a value can be computed from state, make it a getter. If something must happen — a write, a request, a log — put it in an action. This keeps getters predictable and side effects in one place.
You are about to answer a short quiz on getters and actions.