At the end of the previous lesson we took stock of what Vuex costs: mutations that only assign values, action and getter names as strings that the editor cannot check, prefixes and square brackets just to read a value, and a great deal of ceremony for every feature. Pinia is the Vue team's answer to those problems and the officially recommended state management library for Vue 3. It keeps what worked in Vuex (centralised state, derived values, actions, debugging tools, plugins) and gets rid of what was superfluous. In this lesson you will see why it is preferred, how it is installed and how it lives alongside Vuex during a migration, the two styles for defining a store (option stores and setup stores), how to use it in components with storeToRefs, its utilities ($patch, $reset, $subscribe, $onAction), how to combine stores, how to use them outside components (in the router's guards) and what its plugins are. In Colmena you will create the first Pinia store, useRoomsStore, which will replace the Vuex rooms module while bookings and session stay in Vuex for now.
Contents
- Why Pinia
- Installation and coexistence with Vuex
- Defining a store: option stores
- Defining a store: setup stores
- Option store or setup store
- Using a store in components and
storeToRefs - Store utilities:
$patch,$reset,$subscribeand$onAction - Using one store inside another
- Using stores outside components
- Pinia plugins
- Case study:
useRoomsStore
- Why Pinia
Pinia was born in 2019 as an experiment by Eduardo San Martín Morote (a member of the Vue team and the author of Vue Router) to explore what Vuex might look like built on the Composition API. The ideas worked so well that the experiment became what would have been "Vuex 5", and today it is the official library. The name comes from piña, Spanish for pineapple: a pineapple is really a cluster of small individual fruits joined together, just as an application's state is made up of small independent stores.
| Aspect | Vuex 4 | Pinia |
|---|---|---|
| Mutations | Required to change the state | They do not exist: actions (or components) modify the state directly |
| Organisation | A single store divided into namespaced modules | Several independent stores by design; each one has an id |
| Accessing data | Strings: store.getters['rooms/roomById'], dispatch('bookings/createBooking') |
Properties and functions: roomsStore.roomById, bookingsStore.createBooking() |
| Autocompletion and types | Poor: strings are not checked; TypeScript requires manual types | Full inference: the editor knows every property and action (09-02) |
| Composition API | useStore() + computed for every value |
Designed for it; it also supports the Options API |
| Vue DevTools | A plugin for Vuex | Full integration: an inspector per store and a timeline |
| SSR | Possible, with care | First-class support (Nuxt uses it by default, 09-06) |
| Loading stores | Static modules or manual registerModule |
Each store is registered when it is first used: it splits into chunks naturally |
| Size | Larger | Very lightweight (around 1.5 kB compressed, according to its documentation) |
| Status | Maintenance | Recommended; actively developed (version 3, Vue 3 only) |
The essential point: in Pinia, mutations disappear. Pinia achieves the traceability that justified their existence by other means: DevTools records every state change and every action without the need for an intermediate layer.
- Installation and coexistence with Vuex
It is installed as a plugin, with createPinia():
// main.js (generic)
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const app = createApp(App)
app.use(createPinia())
app.mount('#app')createPinia() creates the container for all the stores (the Pinia instance). The stores themselves are not registered here: each one is defined in its own file and created the first time someone uses it.
Pinia and Vuex can coexist in the same application: they are independent plugins, with separate states and separate panels in DevTools. This is what makes an incremental migration possible: create a Pinia store, move one part into it, check that everything works and carry on with the next, without rewriting everything in one go. That is exactly what we will do in Colmena during this lesson and the next.
Install Pinia before Vuex and the router: as you will see, the Vuex store and the guards will use Pinia stores, and they need Pinia to be active.
The folder convention changes too: Pinia stores go in src/stores/ (plural), one file per store. While the two coexist you will have both src/store/ (Vuex) and src/stores/ (Pinia); the one-letter difference is awkward but temporary.
- Defining a store: option stores
A store is defined with defineStore(id, definition). The first style, the option store, looks very much like a Vuex module without mutations:
// src/stores/rooms.js (option store version, for comparison)
import { defineStore } from 'pinia'
import { api } from '@/api'
export const useRoomsStore = defineStore('rooms', {
// State: a function, as in Vuex
state: () => ({
rooms: [],
loading: false,
error: null
}),
// Getters: they receive the state; written with function, they access other getters through this
getters: {
availableRooms: (state) => state.rooms.filter((room) => room.available),
roomById: (state) => (id) => state.rooms.find((room) => room.id === id),
availableCount() {
return this.availableRooms.length
}
},
// Actions: they modify the state directly through this
actions: {
async loadRooms() {
this.loading = true
this.error = null
try {
this.rooms = await api.rooms.fetchRooms()
} catch (error) {
this.error = error.message
} finally {
this.loading = false
}
}
}
})'rooms'is the store's id: unique within the application. It is the equivalent of the namespaced module's name, and it is what you will see in DevTools.useRoomsStore: by convention, the function returned bydefineStoreis exported with the nameuse+ name +Store, like a composable.- Actions use
thisto read and modify the state, the getters and other actions. That is why they must be ordinary functions (not arrow functions). - There is no
commitand there are no mutations:this.loading = trueis a legitimate state change and DevTools records it.
- Defining a store: setup stores
The second style, the setup store, defines the store with a function that works like a component's setup():
// src/stores/rooms.js (setup store version)
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from '@/api'
export const useRoomsStore = defineStore('rooms', () => {
// ref() → state
const rooms = ref([])
const loading = ref(false)
const error = ref(null)
// computed() → getters
const availableRooms = computed(() => rooms.value.filter((room) => room.available))
const roomById = computed(() => (id) => rooms.value.find((room) => room.id === id))
// functions → actions
async function loadRooms() {
loading.value = true
error.value = null
try {
rooms.value = await api.rooms.fetchRooms()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
}
}
// Whatever is returned is public
return { rooms, loading, error, availableRooms, roomById, loadRooms }
})There are only a few rules:
- Each
ref(orreactive) returned is state, eachcomputedis a getter and each function is an action. - You must return all of the state. Pinia only knows about what is returned: an internal
refthat is not returned does not appear in DevTools, cannot be restored in SSR and is not seen by plugins. Non-reactive variables (a promise in progress, a constant) can stay private. - Everything that works in a composable works here:
watch, other composables,inject()of values provided withapp.provide. - Getters with arguments are written as a
computedthat returns a function, just as in Vuex. You could return an ordinary function (function roomById(id)), but Pinia would treat it as an action: it would appear in DevTools and in$onActionevery time it was called.
- Option store or setup store
| Concept | Option store | Setup store |
|---|---|---|
| State | state: () => ({ rooms: [] }) |
const rooms = ref([]) |
| Getter | getters: { available: (state) => ... } |
const available = computed(() => ...) |
| Getter that uses another | function () { return this.other... } |
computed(() => other.value...) |
| Action | actions: { load() { this.x = ... } } |
function load() { x.value = ... } |
| Internal access | this |
Closure variables (rooms.value) |
$reset() |
Included | You have to write it |
| Private state | No | Yes (non-returned variables that are not state) |
watch, composables, inject |
No | Yes |
| Similar to... | Vuex / Options API | Composables / <script setup> |
Recommendation: if you come from Vuex or the Options API, the option store will feel familiar, and it is a perfectly valid choice, especially in mechanical migrations. But setup stores are more flexible (they can use watch and composables) and their code is just like <script setup>, which is the style used throughout the course. In Colmena we will use setup stores.
- Using a store in components and
storeToRefs
storeToRefs6.1 Calling useXStore()
<script setup>
import { computed } from 'vue'
import { useRoomsStore } from '@/stores/rooms.js'
const roomsStore = useRoomsStore()
roomsStore.loadRooms() // an action is a method
const freeCount = computed(() => roomsStore.availableRooms.length)
</script>
<template>
<p v-if="roomsStore.loading">Loading…</p>
<p v-else>{{ freeCount }} free rooms · {{ roomsStore.roomById('nectar')?.name }}</p>
</template>useRoomsStore()returns the store: the first call in the application creates it; subsequent calls return the same instance.- The store is a
reactiveobject:roomsStore.loading(state),roomsStore.availableRooms(getter) androomsStore.loadRooms()(action) are used as properties and methods, with no.value, no prefixes and no strings. The editor autocompletes them. - There is no need to wrap every value in
computedas in Vuex: the store is already reactive, and readingroomsStore.loadingin the template or in a computed property updates by itself.
6.2 Why not to destructure directly
Because the store is a reactive, destructuring has the same problem as in 05-04:
// WRONG: loading and rooms keep the values they have at this instant
const { loading, rooms } = useRoomsStore()6.3 storeToRefs
Pinia offers storeToRefs, which turns the store's state and getters into refs, so that you can destructure them without losing reactivity:
import { storeToRefs } from 'pinia'
const roomsStore = useRoomsStore()
// State and getters: with storeToRefs → refs linked to the store
const { rooms, loading, availableRooms } = storeToRefs(roomsStore)
// Actions: straight from the store (they are functions; they do not need a ref)
const { loadRooms } = roomsStoreconst x = store.x / destructuring the store |
storeToRefs(store) |
computed(() => store.x) |
|
|---|---|---|---|
| Reactive? | No | Yes | Yes |
| State | A copy of the value | A writable ref linked to the store |
Read-only |
| Getters | A copy of the value | A read-only ref |
Read-only |
| Actions | They work (they are bound to the store) | Not included | — |
Unlike toRefs, storeToRefs ignores the actions and the store's other internal properties. And unlike Vuex, writing to those refs is legitimate: loading.value = true modifies the store's state and DevTools records it. This means you can use v-model directly on a store's state:
The fact that you can write to the state from a component does not mean you should do so for everything. For changes that involve logic (validations, API calls, several values at once), create an action: the component stays simpler and the rule lives in a single place. Writing directly is reasonable for simple preferences, such as the catalogue view.
- Store utilities:
$patch, $reset, $subscribe and $onAction
$patch, $reset, $subscribe and $onActionEvery store includes some methods that begin with $ to distinguish them from what the developer defines.
7.1 $patch: several changes at once
// With an object: merges the properties given
roomsStore.$patch({ loading: false, error: 'No connection' })
// With a function: for changes that are not simple assignments (arrays, calculations)
roomsStore.$patch((state) => {
state.rooms.push(newRoom)
state.error = null
})$patch groups the changes into a single entry in the DevTools timeline and into a single notification to subscribers. With an object, arrays are replaced (not merged element by element), so to add to an array you use the function form.
7.2 $reset: back to the initial state
In option stores, store.$reset() comes built in: it calls state() again and replaces the state. In setup stores it does not exist, because Pinia does not know what the initial state of a set of arbitrary refs is; if you need it, you write it and return it:
export const useRoomsStore = defineStore('rooms', () => {
const rooms = ref([])
const loading = ref(false)
function $reset() {
rooms.value = []
loading.value = false
}
return { rooms, loading, $reset }
})Using the name $reset keeps the same interface as option stores, so plugins or code that expect it will work in the same way.
7.3 $subscribe: reacting to state changes
const stopListening = roomsStore.$subscribe((mutation, state) => {
// mutation.type: 'direct' | 'patch object' | 'patch function'
// mutation.storeId: 'rooms'
localStorage.setItem('colmena-catalog-view', state.catalogView)
})It is the equivalent of Vuex's store.subscribe, but per store. Unlike a watch, it runs once per $patch, even if the patch changes several properties. If it is called inside a component, the subscription is removed when the component is unmounted; to keep it, you pass { detached: true } as the second argument.
7.4 $onAction: observing actions
roomsStore.$onAction(({ name, args, after, onError }) => {
const start = performance.now()
after(() => {
console.log(`[Colmena] ${name} finished in ${Math.round(performance.now() - start)} ms`)
})
onError((error) => {
console.warn(`[Colmena] ${name} failed:`, error.message)
})
})The function runs before each action and receives its name (name), its arguments (args), the store itself (store) and two hook registrars: after (when the action finishes, including the promise of an async action) and onError (if it throws or its promise is rejected). It is the equivalent of Vuex's subscribeAction and is used for logging, analytics or measurement.
| Utility | Vuex equivalent | What for |
|---|---|---|
$patch |
A mutation that changes several things | Grouping changes |
$reset |
A hand-written reset mutation |
Returning to the initial state |
$subscribe |
store.subscribe |
Reacting to state changes |
$onAction |
store.subscribeAction |
Observing actions |
$state |
store.state.module |
Reading or replacing the store's whole state |
- Using one store inside another
In Pinia there is no rootState or rootGetters: a store that needs another one uses it, just like a component does:
// A bookings store that needs the catalogue's prices (example)
import { useRoomsStore } from './rooms.js'
export const useBookingsStore = defineStore('bookings', () => {
const roomsStore = useRoomsStore() // at the top level of the setup
const bookings = ref([])
const totalAmount = computed(() =>
bookings.value.reduce((total, b) => total + (roomsStore.roomById(b.roomId)?.hourlyPrice ?? 0), 0)
)
async function loadBookings() {
await roomsStore.loadRooms() // another store's action: an ordinary call
// ...
}
return { bookings, totalAmount, loadBookings }
})- Dependencies are explicit: an
importand a call, which the editor can follow. No'rooms/roomById'strings. - Circular dependencies: if
useBookingsStoreusesuseSessionStoreanduseSessionStoreusesuseBookingsStore, they cannot both read the other's state during theirsetup. The solution is for at least one of them to call the other inside an action or a getter, not at the top level. We will apply this in 05-07.
A Pinia store can also be used from Vuex while the two coexist: inside a module's getter or action, it is enough to call useRoomsStore(). That is the bridge we will use in the case study.
- Using stores outside components
useRoomsStore() needs to know which Pinia instance to look for the store in. Inside a component it works this out by itself (with inject). Outside components, it uses the active Pinia, which app.use(pinia) sets when it is installed. Hence the rule: call useXStore() at the moment you use it, not when the module loads.
// src/router/index.js
// WRONG: runs when the file is imported, before app.use(pinia)
// const roomsStore = useRoomsStore() → error: getActivePinia() was called but there was no active Pinia
// RIGHT: inside the guard, which runs during a navigation (Pinia is already installed)
router.beforeEach((to) => {
const roomsStore = useRoomsStore()
// ...
})The reason is the order of execution: main.js imports router/index.js (and its top-level code runs) before it reaches app.use(createPinia()). The guards, on the other hand, only run when there is a navigation, and the first one is triggered by app.use(router), after Pinia has been installed.
The same applies to any JavaScript module (a service, a utility): call useXStore() inside the function that needs it. In SSR (09-06) this rule is even more important, because each request has its own Pinia instance.
- Pinia plugins
A Pinia plugin is a function that runs for each store when it is created. It receives a context and can add properties to the store, subscribe to its changes or wrap its actions:
// Generic plugin
function myPlugin({ store, options, pinia, app }) {
// store: the newly created store · options: whatever was passed to defineStore
store.$subscribe(() => { /* ... */ })
return { createdAt: Date.now() } // properties added to every store
}
const pinia = createPinia()
pinia.use(myPlugin)The most popular use case is, as in Vuex, persistence. The ecosystem has a very widely used community plugin, pinia-plugin-persistedstate, which is enabled with an option in each store:
// With pinia-plugin-persistedstate (usage example)
export const useSessionStore = defineStore('session', () => { /* ... */ }, {
persist: {
storage: sessionStorage,
pick: ['name', 'email', 'plan', 'role'] // the fields that are saved
}
})- The third argument of
defineStorein a setup store accepts additional options, which plugins read inoptions. That way each store declares what it wants to persist, and the plugin decides how. - The option names depend on the version of the plugin (for example, earlier versions used
pathsinstead ofpick). Always check the documentation for the version you install.
Under the hood, a persistence plugin does the same as the Vuex plugin from 05-05: when the store is created it restores what was saved (with store.$patch) and on every change it saves the specified fields (with store.$subscribe). In the next lesson we will migrate our Vuex plugin to a Pinia plugin of our own, so as to keep exactly the same behaviour.
- Case study:
useRoomsStore
useRoomsStoreWe start the migration with the catalogue: it is the most independent module (it depends on no other) and the one used by the most views. bookings and session will stay in Vuex until the next lesson.
11.1 Installing and registering Pinia
// src/main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia' // NEW
import App from './App.vue'
import router from './router'
import store from './store'
import { CONFIG_KEY } from './keys.js'
import './assets/main.css'
const app = createApp(App)
// ... errorHandler and app.provide unchanged ...
app.use(createPinia()) // NEW: first, so that Vuex and the router can use its stores
app.use(store)
app.use(router)
app.mount('#app')11.2 src/stores/rooms.js
Create the src/stores/ folder and the store as a setup store. It is the translation of the rooms module from 05-05, with its cache, the deduplication and the view preference:
// src/stores/rooms.js
// Room catalogue (Pinia, setup store)
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from '@/api'
const CATALOG_MAX_AGE_MS = 5 * 60 * 1000
export const useRoomsStore = defineStore('rooms', () => {
// --- State ---
const rooms = ref([])
const loadedAt = ref(null) // timestamp of the last successful load
const loading = ref(false)
const error = ref(null)
const catalogView = ref('grid') // 'grid' | 'table' | 'map'
// --- Getters ---
const availableRooms = computed(() => rooms.value.filter((room) => room.available))
const roomById = computed(() => (id) => rooms.value.find((room) => room.id === id))
// --- Actions ---
let pendingLoad = null // private and non-reactive: it is not state
// Loads the catalogue unless there is a fresh copy; does not duplicate requests in progress
function loadRooms({ force = false } = {}) {
const fresh = loadedAt.value !== null && Date.now() - loadedAt.value < CATALOG_MAX_AGE_MS
if (fresh && !force) return Promise.resolve()
if (pendingLoad) return pendingLoad
pendingLoad = (async () => {
loading.value = true
error.value = null
try {
rooms.value = await api.rooms.fetchRooms()
loadedAt.value = Date.now()
} catch (e) {
error.value = e.message
} finally {
loading.value = false
pendingLoad = null
}
})()
return pendingLoad
}
function $reset() {
rooms.value = []
loadedAt.value = null
loading.value = false
error.value = null
catalogView.value = 'grid'
}
return {
rooms, loadedAt, loading, error, catalogView,
availableRooms, roomById,
loadRooms, $reset
}
})Compare it with the Vuex module:
rooms module (Vuex) |
useRoomsStore (Pinia) |
|---|---|
state.list |
rooms (the name reads better: roomsStore.rooms) |
startLoading, setRooms, setError, setCatalogView |
They disappear: the action assigns directly |
loadRooms({ state, commit }, { force }) |
loadRooms({ force }) |
createRoomsModule(api) (factory) |
import { api } from '@/api'; in tests, that module will be replaced (08-02) |
| ~60 lines | ~50 lines, no strings |
11.3 Vuex uses the Pinia store
Remove the rooms module from Vuex. In src/store/index.js, take out its import and its line in modules:
// src/store/index.js
modules: {
bookings: createBookingsModule(api),
session: createSessionModule(api)
},Delete src/store/modules/rooms.js. The bookings module used the Vuex catalogue in two places (rootGetters['rooms/roomById'] and dispatch('rooms/loadRooms', ...)); it will now use the Pinia store. In src/store/modules/bookings.js:
// src/store/modules/bookings.js
import { useRoomsStore } from '@/stores/rooms.js' // NEW
// In getters: monthlyBookingsTotal no longer needs rootGetters for the prices
monthlyBookingsTotal(state, getters) {
const roomsStore = useRoomsStore() // inside the getter, not at the top level
const month = currentMonth()
return getters.myBookings
.filter((b) => isActive(b) && b.date.startsWith(month))
.reduce((total, b) => {
const room = roomsStore.roomById(b.roomId)
return room ? total + room.hourlyPrice * durationHours(b.startTime, b.endTime) : total
}, 0)
},
// In loadBookings, inside the Promise.all
const [bookings] = await Promise.all([
api.bookings.fetchBookings(),
useRoomsStore().loadRooms()
])The Vuex getter is also recalculated when the Pinia catalogue changes: both use Vue's reactivity system, so dependencies are tracked in the same way.
11.4 The catalogue views
In HomeView.vue, replace useStore and the three computed properties:
// HomeView.vue
import { computed, inject } from 'vue'
import { storeToRefs } from 'pinia'
import { useRoomsStore } from '@/stores/rooms.js'
// ... inject(CONFIG_KEY) unchanged ...
const roomsStore = useRoomsStore()
roomsStore.loadRooms()
const { loading, error } = storeToRefs(roomsStore)
const freeRooms = computed(() => roomsStore.availableRooms.length)In RoomsView.vue, replace the block you added in 05-04:
// RoomsView.vue
import { storeToRefs } from 'pinia'
import { useRoomsStore } from '@/stores/rooms.js'
const roomsStore = useRoomsStore()
roomsStore.loadRooms()
// catalogView, renamed to currentView so as not to touch the template; it is a WRITABLE ref
const { loading, error, catalogView: currentView } = storeToRefs(roomsStore)
const catalog = computed(() =>
floorFilter.value === null
? roomsStore.rooms
: roomsStore.rooms.filter((room) => room.floor === floorFilter.value)
)
function reloadRooms() {
roomsStore.loadRooms({ force: true })
}Note currentView: in Vuex it needed a computed with a get and a set that committed a mutation; with Pinia, storeToRefs returns a writable ref and the template (@click="currentView = key") writes to the store directly.
In RoomDetailView.vue:
// RoomDetailView.vue
import { storeToRefs } from 'pinia'
import { useRoomsStore } from '@/stores/rooms.js'
const roomsStore = useRoomsStore()
roomsStore.loadRooms()
const { loading, error } = storeToRefs(roomsStore)
const room = computed(() => roomsStore.roomById(id) ?? null)
const notFound = computed(() => roomsStore.loadedAt !== null && room.value === null)
const otherRooms = computed(() => roomsStore.rooms.filter((r) => r.id !== id))
function reload() {
roomsStore.loadRooms({ force: true })
}And in DashboardBookingsView.vue, roomNameById used the Vuex getter rooms/roomById, which no longer exists:
// DashboardBookingsView.vue
import { useRoomsStore } from '@/stores/rooms.js'
const roomsStore = useRoomsStore()
function roomNameById(id) {
return roomsStore.roomById(id)?.name ?? id
}In the first three views there is no Vuex useStore left; DashboardBookingsView still uses it for the bookings.
11.5 The router's guards check the catalogue
The checkRoomExists and checkRoomAvailable guards from 04-06 used the local data from src/data/rooms.js, because it was synchronous. Now that the catalogue lives in a store with a cache, they can check the same data as the application, by calling useRoomsStore() inside each guard. In src/router/index.js, remove import { rooms } from '@/data/rooms.js' and:
// src/router/index.js
import { useRoomsStore } from '@/stores/rooms.js'
// The room does not exist: show the 404 page while keeping the URL
async function checkRoomExists(to) {
const roomsStore = useRoomsStore() // inside the guard: Pinia is already active
await roomsStore.loadRooms() // instant if the catalogue is cached
if (roomsStore.rooms.length === 0) return // no catalogue (network failure): the server will validate on booking
if (!roomsStore.roomById(to.params.roomId)) {
return {
name: 'not-found',
params: { pathMatch: to.path.substring(1).split('/') },
query: to.query,
hash: to.hash
}
}
}
// The room is not accepting bookings: go to its spec sheet, which explains why
function checkRoomAvailable(to) {
const room = useRoomsStore().roomById(to.params.roomId)
if (room && !room.available) {
return { name: 'room-detail', params: { id: room.id } }
}
}checkRoomExistsis now asynchronous: if someone opens/book/nectardirectly, the guard waits for the catalogue to arrive. As we saw in 04-06, the router waits for guards that return promises.- If the catalogue could not be loaded, the guard lets the navigation through instead of showing a false 404: the API will reject an impossible booking (05-02).
checkRoomAvailablecan be synchronous: it runs after the previous one, with the catalogue already loaded. It checksroom &&because of the previous case.- The global session guard does not change: it still reads the Vuex
sessionmodule withstore.getters['session/active'].
11.6 Try it
- Open Vue DevTools: there are now two state panels, the Vuex one (with
bookingsandsession) and the Pinia one (with theroomsstore). Theroomsstore appears as soon as a view uses it for the first time. - Browse the home page, the catalogue and the spec sheets: the catalogue is requested only once, as before. In the Pinia timeline you will see the
loadRoomsaction and the state changes. - Change the catalogue view to "Table": in the Pinia inspector,
catalogViewchanges to'table'without any mutation in between. Open a spec sheet and come back: it is kept. - Sign in and open "My bookings": the room names and the month's amount work; Vuex is reading the Pinia store.
- Reload directly on
/book/basement: the guard waits for the catalogue and shows the 404 page while keeping the URL. Try/book/enjambre: it takes you to its spec sheet. - Try the top-level error: temporarily add
const test = useRoomsStore()at the beginning ofsrc/router/index.js(outside any function). The application does not start and the console shows Pinia's no-active-instance error. Remove it. - In the console:
const pinia = document.querySelector('#app').__vue_app__.config.globalProperties.$piniaandpinia.state.value.roomsshows the store's state.
Common Mistakes and Tips
- Destructuring the store without
storeToRefs. The variables lose reactivity. For state and getters,storeToRefs; actions can be destructured straight from the store. - Passing actions through
storeToRefs. It does not include them; take them from the store directly. - Not returning all the state in a setup store. A
refthat is not returned does not appear in DevTools, is not seen by plugins and does not work with SSR. - Defining getters with arguments as ordinary functions in a setup store. They work, but Pinia treats them as actions (they appear in DevTools and in
$onActionon every call). Use acomputedthat returns a function. - Calling
useXStore()at the top level of a module that is imported beforeapp.use(pinia)(the router, a service). Call it inside the function that uses it. - Expecting
$reset()to exist in a setup store. You have to write it. - Using
$patchwith an object to add to an array. It replaces it. Use the function form. - Writing to the state from any component because "Pinia allows it". For changes that involve logic, an action. The discipline that mutations imposed is still a good idea; now it is a design decision, not an obligation.
- Tip: use the same name for the store's id and for its file (
'rooms'insrc/stores/rooms.js), and the nameuseRoomsStorefor the function. It makes each store easy to find in DevTools and in the code. - Tip: when migrating, start with the most independent store, as we have done with
rooms. Every step must leave the application working.
Exercises
Exercise 1. Rewrite useRoomsStore as an option store with the same state, getters and actions (including the cache and the deduplication). Where would you keep pendingLoad? What do you gain and what do you lose compared with the setup store?
Exercise 2. Make the chosen catalogue view survive a reload: read the initial value from localStorage (key colmena-catalog-view) inside the setup store, checking that it is one of the three allowed values, and save it every time it changes. Do it in two ways: with a watch inside the setup store and with $subscribe from main.js. When would you prefer each one?
Exercise 3. Add a performance log to useRoomsStore with $onAction that warns in the console (in development only) when loadRooms takes longer than 1 second. Register it in main.js right after installing Pinia. What problem would you have if you registered it at the top level of src/stores/rooms.js?
Solutions
Solution 1.
// src/stores/rooms.js (option store)
import { defineStore } from 'pinia'
import { api } from '@/api'
const CATALOG_MAX_AGE_MS = 5 * 60 * 1000
let pendingLoad = null // at module level: it cannot be state (it is not serialisable)
export const useRoomsStore = defineStore('rooms', {
state: () => ({
rooms: [],
loadedAt: null,
loading: false,
error: null,
catalogView: 'grid'
}),
getters: {
availableRooms: (state) => state.rooms.filter((room) => room.available),
roomById: (state) => (id) => state.rooms.find((room) => room.id === id)
},
actions: {
loadRooms({ force = false } = {}) {
const fresh = this.loadedAt !== null && Date.now() - this.loadedAt < CATALOG_MAX_AGE_MS
if (fresh && !force) return Promise.resolve()
if (pendingLoad) return pendingLoad
pendingLoad = (async () => {
this.loading = true
this.error = null
try {
this.rooms = await api.rooms.fetchRooms()
this.loadedAt = Date.now()
} catch (e) {
this.error = e.message
} finally {
this.loading = false
pendingLoad = null
}
})()
return pendingLoad
}
}
})pendingLoad goes at module level, because the option store does not have a closure of its own in which to keep private variables. The difference is that, if there were several Pinia instances (SSR, tests in parallel), they would share that variable; in the setup store, each instance has its own. You gain $reset() for free and a structure familiar to anyone coming from Vuex; you lose private per-instance state, the ability to use watch and composables, and consistency with the <script setup> style of the rest of the project. Note that the inner arrow function assigned to pendingLoad keeps the action's this.
Solution 2.
// src/stores/rooms.js, inside the setup
const VALID_VIEWS = ['grid', 'table', 'map']
const VIEW_KEY = 'colmena-catalog-view'
function readSavedView() {
try {
const saved = localStorage.getItem(VIEW_KEY)
return VALID_VIEWS.includes(saved) ? saved : 'grid'
} catch {
return 'grid' // storage blocked
}
}
const catalogView = ref(readSavedView()) // replaces ref('grid')
// Option 1: a watch inside the setup (add watch to the vue import)
watch(catalogView, (view) => localStorage.setItem(VIEW_KEY, view))Inside the setup the store object does not exist yet (you are building it), so you cannot call its $subscribe; on the other hand, a watch on the ref is straightforward and sits right next to the data: that is one of the advantages of setup stores. Option 2, with $subscribe, is registered from outside the store, for example in main.js; it is preferable when you want to listen to all of the store's state with a single subscription (grouping the changes of each $patch) or when persistence should not be part of the store, which is exactly what a plugin will do:
// main.js, after app.use(pinia)
const roomsStore = useRoomsStore(pinia)
roomsStore.$subscribe((mutation, state) => {
localStorage.setItem('colmena-catalog-view', state.catalogView)
}, { detached: true })(Here pinia is the constant holding the result of createPinia(); passing it to useRoomsStore(pinia) is the explicit way of specifying the instance outside components.)
Solution 3.
// src/main.js
import { createPinia } from 'pinia'
import { useRoomsStore } from './stores/rooms.js'
const pinia = createPinia()
app.use(pinia)
if (import.meta.env.DEV) {
useRoomsStore(pinia).$onAction(({ name, after }) => {
if (name !== 'loadRooms') return
const start = performance.now()
after(() => {
const duration = performance.now() - start
if (duration > 1000) console.warn(`[Colmena] loadRooms took ${Math.round(duration)} ms`)
})
})
}At the top level of src/stores/rooms.js you would have the problem from section 9: that code runs when the file is imported, when there is no active Pinia yet (and even if there were, you would be creating the store before anyone needed it). Also, after runs when the promise returned by loadRooms resolves; if the action reuses a load in progress, you will measure the waiting time of that call, which is what its caller perceives.
Conclusion
Pinia is the recommended state management library for Vue 3: it does away with mutations, organises the state into independent stores identified by an id, is used with properties and methods instead of strings, offers type inference, full integration with Vue DevTools, SSR support and a minimal size, and can coexist with Vuex during a migration. A store is defined with defineStore, either as an option store (state, getters, actions with this) or as a setup store (ref for the state, computed for the getters, functions for the actions, returning everything that is public), which is the style we will use. In components it is used by calling useXStore(), and destructured with storeToRefs. Every store offers $patch, $reset (which you have to write in setup stores), $subscribe and $onAction; one store uses another simply by calling it; outside components, useXStore() is called inside the function that needs it, as in the router's guards; and plugins extend every store, for example to persist its state. In Colmena, useRoomsStore (in src/stores/rooms.js) has replaced the Vuex rooms module: it is used by HomeView, RoomsView, RoomDetailView, DashboardBookingsView, the booking route's guards and even the Vuex bookings module.
The application now has a foot in each library: the catalogue in Pinia, the bookings and the session in Vuex, and the bookings module building a bridge between the two. That is a normal and safe situation during a migration, but it should not last. In the next lesson, Migrating from Vuex to Pinia, we will complete the journey with an orderly strategy: we will migrate bookings (with its optimistic cancellation and its persistence) and session (with the router guard), update the components and uninstall Vuex.
Vue.js Course
Module 1: Introduction to Vue.js
- What Is Vue.js?
- Setting Up the Development Environment
- Creating Your First Vue Application
- Understanding the Vue Instance: Application, Components and Lifecycle
- Options API and Composition API: Two Ways to Write Components
Module 2: Vue.js Basics
- Template Syntax
- Reactivity: ref and reactive
- Data Binding
- Event Handling
- Computed Properties and Watchers
- Class and Style Bindings
- Conditional Rendering
- List Rendering
- Forms with v-model
Module 3: Vue.js Components
- Introduction to Components
- Props and Custom Events
- v-model on Your Own Components
- Slots
- Template Refs and Fallthrough Attributes
- Dynamic and Async Components
- Component Communication
Module 4: Vue Router
- Introduction to Vue Router
- Setting Up Vue Router
- Dynamic Routes
- Nested Routes
- Programmatic Navigation and Query Parameters
- Navigation Guards
Module 5: State Management with Vuex and Pinia
- Introduction to Vuex
- State, Getters, Mutations and Actions
- Vuex Modules
- Using Vuex in Components
- Advanced Vuex Patterns
- Pinia: The Recommended State Management for Vue 3
- Migrating from Vuex to Pinia
Module 6: Vue.js Directives
Module 7: Vue.js Plugins
Module 8: Testing in Vue.js
- Unit Testing with Vue Test Utils and Vitest
- Mocking Dependencies
- Testing Composables and Stores
- End-to-End Testing with Cypress
Module 9: Advanced Vue.js Concepts
- The Vue 3 Composition API in Depth: Composables and Logic Reuse
- Vue with TypeScript
- Render Functions and JSX
- Transitions and Animations
- Teleport, Suspense and Error Handling
- Server-Side Rendering (SSR) with Nuxt
- Performance Optimization
