The Three Store Essentials: state, getters, and actions
🎯 Introduction
By the end of this article, you will understand the responsibilities of a Pinia store’s three core parts: state, getters, and actions. You will be able to write a well-structured store with clearly defined responsibilities.
🧱 Basic Store Structure
A typical store looks like this:
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
getters: {
double() {
return this.count * 2;
},
},
actions: {
add() {
this.count++;
},
},
});
Each part has a specific role:
- state: stores data
- getters: compute values from data
- actions: update data or run business logic
state holds the shelves, getters provide price labels and reports, and actions are the warehouse operators.📦 Storing Data with state
state must be a function that returns an object. Pinia automatically makes that object reactive.
export const useUserStore = defineStore('user', {
state: () => ({
name: 'Alex',
age: 20,
}),
});
Read the state in a component:
<template>
<p>{{ user.name }}{{ user.age }} years old</p>
</template>
<script setup>
import { useUserStore } from './stores/user.js';
const user = useUserStore();
</script>
state as a function returning an object. Using an object directly could cause multiple application instances to share data and interfere with each other’s state.⚡ Computing Values with getters
Methods in getters compute values from state and cache their results. As long as their state dependencies remain unchanged, repeated access does not recompute the value.
export const useUserStore = defineStore('user', {
state: () => ({
firstName: 'Alex',
lastName: 'Smith',
}),
getters: {
fullName() {
return this.firstName + this.lastName;
},
},
});
Usage:
<template>
<p>Full name: {{ user.fullName }}</p>
</template>
this.xxx to access state inside a getter. Getters can also access other getters, such as this.otherGetter.🛠 Updating Data with actions
Define methods that update state in actions. They can perform simple updates or encapsulate more complex logic.
export const useCounterStore = defineStore('counter', {
state: () => ({
count: 0,
}),
actions: {
add() {
this.count++;
},
addN(n) {
this.count += n;
},
reset() {
this.count = 0;
},
},
});
Call the actions in a component:
<template>
<p>{{ counter.count }}</p>
<button @click="counter.add">Add 1</button>
<button @click="counter.addN(5)">Add 5</button>
<button @click="counter.reset">Reset</button>
</template>
this.count inside an action. There is no need to commit a mutation as you would in Vuex, which makes Pinia easier to work with.💡 Choosing the Right Tool
| Scenario | Use | Examples |
|---|---|---|
| Storing raw data | state | count, userInfo |
| Computing values from data | getters | double, fullName |
| Updating data or running logic | actions | add, login |
❓ Questions and Answers
Q1: Both getters and actions can access state. How do they differ?
Getters are read-only: they compute and return derived values. Actions update state. One computes; the other changes data.
Q2: Can a getter call an action?
This is not recommended. Getters should perform pure computations without side effects. Use actions for side effects.
Q3: Can an action access a getter?
Yes, using this.xxx.
Q4: Can state contain functions?
This is not recommended. Keep data in state and functions in actions.
🧪 Exercise
Complete the following useTodoStore with:
- A
todosarray whose items haveid,text, anddoneproperties. - A
finishedCountgetter that returns the number of completed items. - An
addTodo(text)action that adds an item. - A
toggle(id)action that toggles the matching item’sdonevalue.
import { defineStore } from 'pinia';
export const useTodoStore = defineStore('todo', {
state: () => ({
todos: [],
}),
getters: {
// Implement finishedCount here
},
actions: {
// Implement addTodo and toggle here
},
});
🎉 You now understand the three store essentials! Next, we will learn how to use stores in components, especially how to avoid losing reactivity.
