Actions & Getters

Methods That Mutate, Computeds That Derive

Actions & Getters

In setup-style Pinia stores, actions are just functions and getters are just computed values — async, composable, and fully typed.

4 min read Level 2/5 #vue#pinia#actions
What you'll learn
  • Define async actions that fetch data
  • Derive state with computed getters
  • Reset a store when needed

Actions are the methods that mutate or load state. Getters are computed values derived from state. In setup-style Pinia, both are plain Composition API.

Async Actions

Actions can be async — return a promise and components can await them.

import { defineStore } from 'pinia'
import { ref } from 'vue'

interface User { id: number; name: string; active: boolean }

export const useUsers = defineStore('users', () => {
  const users = ref<User[]>([])
  const loading = ref(false)
  const error = ref<string | null>(null)

  async function fetchAll() {
    loading.value = true
    error.value = null
    try {
      users.value = await fetch('/api/users').then(r => r.json())
    } catch (e: any) {
      error.value = e.message
    } finally {
      loading.value = false
    }
  }

  return { users, loading, error, fetchAll }
})

Getters as Computeds

Wrap derived state in computed and return it from the store.

import { computed } from 'vue'

const active = computed(() => users.value.filter(u => u.active))
const count = computed(() => users.value.length)

return { users, active, count, fetchAll }

Resetting

Setup stores don’t have a built-in $reset. Either expose your own reset function or stick with the options syntax if you need it.

function $reset() {
  users.value = []
  loading.value = false
  error.value = null
}

Subscribing

For debugging or syncing to localStorage, store.$subscribe((mutation, state) => { ... }) fires on every state change.

Modular Stores →