Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 38 ยท Getters and Actions

Actions

Learn Pinia actions: methods with this, calling actions from components, composing actions, validation and early returns, and why actions beat scattered state writes.

Actions are the methods of a store. If state is the data and getters are the derived values, actions are the things you can do: add an item, sign in, mark a todo as done. They are where the logic of your app lives. In Pinia, actions are the counterpart of Vuex mutations and actions rolled into one, with none of the ceremony.

Defining an action

In an options store, actions go in the actions object. Inside them this is the store, so you can read and write state, call getters, and call other actions:

JavaScript
export const useTodoStore = defineStore("todos", {
  state: () => ({ todos: [], nextId: 1 }),
  getters: {
    openCount: (state) => state.todos.filter((t) => !t.done).length,
  },
  actions: {
    add(text) {
      const clean = text.trim();
      if (clean === "") return;
      this.todos.push({ id: this.nextId++, text: clean, done: false });
    },
    toggle(id) {
      const todo = this.todos.find((t) => t.id === id);
      if (todo) todo.done = !todo.done;
    },
    removeDone() {
      this.todos = this.todos.filter((t) => !t.done);
    },
  },
});

Use arrow functions only if you do not need this; they have none. Method syntax (as above) is the safe default.

Calling actions

Call an action as a method on the store. There is no dispatch and no string name:

JavaScript
const todos = useTodoStore();
todos.add("Write a lesson");
todos.toggle(1);

You can call actions from components, from other actions, from router guards and from plain JavaScript modules. They are just functions that happen to know their store.

A todo store with three actions

Add a few todos, tick some and press "Remove done". All the rules about todos live in the store; the component only collects input and calls actions.

Why not change state from components?

Pinia allows todos.todos.push(...) straight from a component. For one-off cases that is fine. But as soon as the same change appears in two places, or has a rule attached (trim the text, ignore empty, assign an id), it belongs in an action:

  • One place to fix. A rule changes once, not in every component.
  • Testable. You can test add(" ") without mounting a component.
  • Named. todos.removeDone() reads better than a filter expression in a template.
  • Hookable. Actions can be observed with $onAction for logging and analytics.

Actions can call each other

Because this is the whole store, one action can reuse another:

JavaScript
actions: {
  add(text) { /* ... */ },
  addMany(texts) {
    texts.forEach((t) => this.add(t));
  },
},

Keep each action small and give it one job. A big action that does validation, fetching, formatting and cross-store updates is hard to read; split it into smaller actions or helper functions.

Return values and early exit

Actions may return anything. Returning a value is handy for reporting success:

JavaScript
actions: {
  add(text) {
    const clean = text.trim();
    if (clean === "") return false;
    this.todos.push({ id: this.nextId++, text: clean, done: false });
    return true;
  },
},
JavaScript
if (!todos.add(input)) {
  showError("Type something first");
}

Throwing an error is better when failing is unexpected, because the caller can try/catch it. Return a value when "no" is a normal answer.

Validate at the boundary

Actions are a good place to validate and normalize input. They are the only code that writes the state, so they can promise that the state is always valid:

Actions that protect the state

Try to withdraw 500: the action throws, the state stays untouched and the component shows the message. The balance can never go negative, no matter which component calls withdraw.

Actions and this pitfalls

  • Detached methods lose this. const { add } = todos works in Pinia (actions are bound to the store), so destructuring actions is safe. Destructuring state is not; use storeToRefs for that.
  • Arrow functions have no store this. Use method syntax when you need it.
  • Async actions are ordinary async methods; see the next lesson.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is this inside an options-store action?

    Pinia binds this to the store, so you can reach state, getters and other actions.
  2. 2. Which is the best place for a rule such as 'ignore empty todo text'?

    An action is the single place that writes the state, so it can enforce the rule once.
  3. 3. Is it safe to destructure an action from a store, like const { add } = store?

    Pinia wraps actions so that they keep working when detached. State, however, loses reactivity when destructured.
  4. 4. An action should signal an unexpected failure. What is a good way?

    A thrown error lets the caller use try/catch and keeps the state untouched.

Summary

  • Actions are store methods; this is the store.
  • Call them like plain methods from anywhere.
  • Put rules, validation and multi-step changes in actions rather than in components.
  • Actions can call each other, return values or throw errors.
  • Destructuring actions is safe, destructuring state is not.

Next: Async Actions and API Calls