Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 38 ยท Getters and Actions

Watching Actions with $onAction

Use store.$onAction to run code before and after every action, read its name and arguments, handle success and errors, measure timing and write a logger or analytics hook.

$subscribe lets you watch state. $onAction lets you watch actions: every time any action of a store is called, Pinia tells you its name, its arguments, and later what happened. This is the right tool for logging, timing, analytics and guarding against failures, because you can add it without touching the actions themselves.

The callback

JavaScript
const unsubscribe = store.$onAction(({ name, store, args, after, onError }) => {
  // runs BEFORE the action starts
  after((result) => {
    // runs when the action finishes (after a returned promise resolves)
  });
  onError((error) => {
    // runs if the action throws (or its promise rejects)
  });
});

The object passed to your callback contains:

Property Meaning
name the action's name, for example "add"
store the store the action belongs to
args an array of the arguments the action was called with
after(cb) registers cb(result) for success; for async actions it waits for the promise
onError(cb) registers cb(error) for failure

The callback itself runs before the action body. The hooks you register in it run afterwards.

sequenceDiagram
    participant C as Caller
    participant P as Pinia
    participant H as $onAction callback
    participant A as Action body
    C->>P: store.add("milk")
    P->>H: { name, args, after, onError }
    H-->>P: registers after / onError
    P->>A: runs the action
    A-->>P: returns or throws
    P->>H: after(result) or onError(error)
    P-->>C: result

The callback runs first. after and onError fire when the action ends.

A logger in a few lines

Logging every action

Notice that the async saveAll logs "ok" about 400 ms after it starts, because after waits for the promise. Notice also that the failing add is reported through onError even though the component swallows the exception.

Measuring how long an action takes

Because you see both the start and the end, timing is trivial:

JavaScript
store.$onAction(({ name, after, onError }) => {
  const started = performance.now();
  const finish = () => console.log(`${name} took ${(performance.now() - started).toFixed(0)} ms`);
  after(finish);
  onError(finish);
});

The same shape covers analytics ("user pressed checkout"), audit logs, and automatic error reporting to a service.

Rules to remember

  • Return values. after receives the action's resolved result but cannot change it.
  • Errors. onError observes an error; it does not swallow it. The caller still receives the exception.
  • One callback per store, many allowed. You may register several $onAction listeners; each one sees every action.
  • Lifetime. Like $subscribe, an $onAction registered in a component is removed when the component unmounts. Pass true as the second argument (store.$onAction(cb, true)) to detach it from the component and keep it for the life of the store.
  • Other stores. The listener sees only the actions of the store you called it on. To log everything, use a plugin (covered later in the course), which can attach the same hook to every store.

A guard that blocks actions

$onAction cannot cancel an action. To refuse, put the check inside the action. A common alternative for cross-cutting rules (for example "no writes while offline") is to wrap actions in a plugin, which is also covered later. For this chapter, remember that $onAction is for observing.

Try it: a timing report

Timing an async action

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does the $onAction callback itself run?

    It runs first. Use after() and onError() to run code when the action ends.
  2. 2. For an async action, when does after(cb) call cb?

    Pinia waits for the promise, so cb receives the resolved value.
  3. 3. Does onError stop the exception from reaching the caller?

    onError is for observation, such as logging. The caller still gets the error.
  4. 4. How do you keep an $onAction listener alive after the component unmounts?

    $onAction(cb, true) detaches the listener from the component, so it lives as long as the store.

Summary

  • store.$onAction(cb) observes every action of that store.
  • The callback gets name, args, store, after and onError.
  • It runs before the action; hooks run after success or failure.
  • It observes and cannot cancel or change results.
  • Typical uses: logging, timing, analytics and error reporting.

Next: Stores Using Other Stores