Actions

Actions are the equivalent of methods in components. They can be defined with the actions property in defineStore() and they are perfect to define business logic:

export const useStore = defineStore({
  id: 'main',
  state: () => ({
    counter: 0,
  }),
  actions: {
    increment() {
      this.counter++
    },
    randomizeCounter() {
      this.counter = Math.round(100 * Math.random())
    },
  },
})

Like getters, actions get access to the whole store instance through this with full typing (and autocompletion ✨) support.

Actions are invoked like methods:

export default defineComponent({
  setup() {
    const main = useMainStore()
    // call the action as a method of the store
    main.randomizeCounter()

    return {}
  },
})

Accessing other stores actions

To use another store, you can directly use it inside of the action:

import { useAuthStore } from './auth-store'

export const useSettingsStore = defineStore({
  id: 'settings',
  state: () => ({
    // ...
  }),
  actions: {
    async fetchUserPreferences(preferences) {
      const auth = useAuthStore()
      if (auth.isAuthenticated) {
        this.preferences = await fetchPreferences()
      } else {
        throw new Error('User must be authenticated')
      }
    },
  },
})

Usage with setup()

You can directly call any action as a method of the store:

export default {
  setup() {
    const store = useStore()

    store.randomizeCounter()
  },
}

Usage with the options API

If you are not using the composition API, and you are using computed, methods, ..., you can use the mapActions() helper to map actions properties as methods in your component:

import { mapActions } from 'pinia'

export default {
  methods: {
    // gives access to this.increment() inside the component
    // same as calling from store.increment()
    ...mapActions(useStore, ['increment'])
    // same as above but registers it as this.myOwnName()
    ...mapActions(useStore, { myOwnName: 'doubleCounter' }),
  },
}

Watching actions

Give feedback about $onAction()

It is possible to observe actions and their outcome with store.$onAction(). This

Here is an example that logs before running actions and after they resolve/reject.

const unsubscribe = someStore.$onAction(
  ({
    name, // name of the action
    store, // store instance, same as `someStore`
    args, // array of parameters passed to the action
    after, // hook after the action returns or resolves
    onError, // hook if the action throws or rejects
  }) => {
    // a shared variable for this specific action call
    const startTime = Date.now()
    // this will trigger before an action on `store` is executed
    console.log(`Start "${name}" with params [${args.join(', ')}].`)

    // this will trigger if the action succeeds and after it has fully run.
    // it waits for any returned promised
    after((result) => {
      console.log(
        `Finished "${name}" after ${
          Date.now() - startTime
        }ms.\nResult: ${result}.`
      )
    })

    // this will trigger if the action throws or returns a promise that rejects
    onError((error) => {
      console.warn(
        `Failed "${name}" after ${Date.now() - startTime}ms.\nError: ${error}.`
      )
    })
  }
)

// manually remove the listener
unsubscribe()

By default, action listeners are bound to the component where they are added (if the store is inside a component's setup()). Meaning, they will be automatically removed when the component is unmounted.