Colmena now has a foot in each library: the catalogue is in the Pinia store useRoomsStore, while the bookings and the session are still in Vuex modules, and the bookings module acts as a bridge between the two. This is the situation you will find yourself in on many real projects: an application with years of Vuex code that the team wants to move to Pinia without halting development or risking a big-bang rewrite. In this lesson you will complete the migration incrementally: you will define a strategy and an order, you will have a complete mapping table between Vuex and Pinia concepts to hand, you will migrate the bookings module step by step (with its optimistic cancellation and its persistence) and then the session module (with the router guard), you will update the components and, finally, you will uninstall Vuex. You will finish with a checklist, the typical risks of a migration and the final public API of Colmena's three stores, which is what the rest of the course will use.

Contents

  1. An incremental migration strategy
  2. Mapping table between Vuex and Pinia
  3. Step 1: the persistence plugin, to Pinia
  4. Step 2: the bookings module → useBookingsStore
  5. Step 3: the session module → useSessionStore
  6. Step 4: removing Vuex
  7. Checklist and typical risks
  8. The public API of Colmena's stores

  1. An incremental migration strategy

1.1 Why incremental

A "big-bang" migration (rewriting every module on a branch and merging it at the end) looks quicker, but it carries serious risks in a real application: the branch drifts away from the main line of development for weeks, conflicts pile up, and on merge day dozens of files change at once, so any bug is hard to pin down. An incremental migration takes advantage of the fact that Pinia and Vuex coexist (05-06):

  • One module at a time. Each step is a small change that can be reviewed and deployed.
  • The application works after every step. The migration can be paused (for an emergency) without leaving anything broken.
  • The bridges are temporary. While two related modules are in different libraries, one uses the other through an explicit bridge, which is removed in the next step.
flowchart LR
    A["Phase 0<br/>Everything in Vuex"] --> B["Phase 1 (05-06)<br/>rooms → Pinia<br/>bookings and session in Vuex"]
    B --> C["Step 2<br/>bookings → Pinia<br/>session in Vuex"]
    C --> D["Step 3<br/>session → Pinia<br/>Vuex empty"]
    D --> E["Step 4<br/>Vuex uninstalled"]

1.2 Ordering criteria

Which module should you start with? Draw the dependencies between modules and migrate first the ones that depend on the fewest:

Criterion Why
Fewest dependencies first (the leaves of the graph) A Pinia store is easy to use from Vuex; the reverse bridge is more awkward
Most used by the views The improvement shows sooner and the pattern is validated against many cases
Least risk Start with read-only data (a catalogue) before critical flows (session, payments)
With tests If a module has tests, they let you check that its behaviour does not change

In Colmena, the dependencies are:

flowchart LR
    R["bookings"] -->|"prices, loadRooms"| S["rooms"]
    R -->|"myBookings: name and role"| SE["session"]
    SE -->|"signIn → loadBookings<br/>signOut → clear"| R
    G["Router guards"] --> SE
    G --> S

rooms depends on nobody: that is why it went first. bookings and session depend on each other; we choose to migrate bookings first because its dependency on session is a read (a getter) and easy to bridge, and we leave session until last because the router uses it too, and the router is the most delicate piece.

  1. Mapping table between Vuex and Pinia

This table is the reference for any migration:

Vuex Pinia Notes
createStore({ modules }) + app.use(store) createPinia() + app.use(pinia) Stores are not registered: they are created when used
A module with namespaced: true A store with defineStore('id', ...) The namespace becomes the store's id
state: () => ({ ... }) ref() in a setup store (or state in an option store) You have to return all the state
getters: { x: (state) => ... } computed() Getters with arguments: computed(() => (arg) => ...)
getters with (state, getters, rootState, rootGetters) Use other stores inside the computed rootGetters['rooms/roomById'] → useRoomsStore().roomById
mutations They disappear Their assignment moves into the action, or into a private function if it is repeated
actions: { x({ commit, state }, payload) } Functions in the setup store No context; several arguments allowed
commit('x', payload) Assign the state (x.value = ...) or $patch Inside the store
dispatch('x', payload) A direct call: store.x(payload) Returns whatever the function returns
dispatch('other/x', p, { root: true }) useOtherStore().x(p) An explicit dependency with import
rootState.session.name useSessionStore().name —
store.registerModule (dynamic registration) Unnecessary Each store is created when used; with lazy loading, its code goes into the chunk that imports it
useStore() + computed(() => store.state.m.x) const s = useMStore() and s.x, or storeToRefs(s) —
computed({ get, set: commit }) for v-model storeToRefs (writable ref) or v-model="s.x" —
mapState('m', [...]) / mapGetters Pinia's mapState(useMStore, [...]) Pinia treats state and getters alike
mapMutations mapWritableState(useMStore, [...]) or actions —
mapActions('m', [...]) Pinia's mapActions(useMStore, [...]) —
this.$store mapStores(useMStore) → this.mStore For the Options API
createNamespacedHelpers Unnecessary Each Pinia helper already receives its store
Vuex plugin (store) => { store.subscribe(...) } Pinia plugin ({ store, options }) => { store.$subscribe(...) } Runs for each store
store.subscribe store.$subscribe Per store
store.subscribeAction store.$onAction Per store
store.replaceState store.$patch / store.$state = ... —
A hand-written reset mutation $reset() You have to write it in a setup store
strict: true Does not exist Pinia allows the state to be written from outside; discipline is a convention
createLogger DevTools (or a plugin with $onAction/$subscribe) —
createAppStore({ api }) (a factory for injecting dependencies) Import @/api and replace it in tests 08-02, 08-03

A note on the Options API: if the project has many components written with it, you do not need to rewrite them to migrate the store. Pinia's helpers let you change just the computed/methods block:

// Before (Vuex)
computed: { ...mapState('rooms', { rooms: 'list' }), ...mapGetters('rooms', ['availableRooms']) },
methods: { ...mapActions('rooms', ['loadRooms']) }

// After (Pinia): import { mapState, mapActions, mapStores } from 'pinia'
computed: {
  ...mapStores(useRoomsStore),                          // this.roomsStore (id + 'Store')
  ...mapState(useRoomsStore, ['rooms', 'availableRooms']) // state and getters, alike
},
methods: { ...mapActions(useRoomsStore, ['loadRooms']) }

Notice that Pinia's helpers have the same names as Vuex's, but they are imported from 'pinia' and they receive the store (the useXStore function), not a string. A typical mistake in a migration is to leave the import from 'vuex' in place.

  1. Step 1: the persistence plugin, to Pinia

Before moving the bookings and the session, which are persisted, we need the equivalent of the Vuex plugin from 05-05. The design difference is that a Pinia plugin runs for each store, so instead of a central list of rules, each store will declare what it wants to persist with an option in the third argument of defineStore.

Create src/stores/plugins/persistence.js:

// src/stores/plugins/persistence.js
// Pinia plugin: persists the fields each store declares in its "persistence" option.
// Usage: defineStore('id', setup, { persistence: { storage: sessionStorage, key: '...', fields: [...] } })
export function persistence({ store, options }) {
  const config = options.persistence
  if (!config) return // this store does not ask for persistence

  const { storage, key, fields } = config

  // 1. When the store is created: restore what was saved
  try {
    const saved = JSON.parse(storage.getItem(key))
    if (saved) store.$patch(saved)
  } catch {
    storage.removeItem(key) // corrupted data: discarded
  }

  // 2. On every state change: save only the specified fields
  store.$subscribe(
    (mutation, state) => {
      const data = Object.fromEntries(fields.map((field) => [field, state[field]]))
      storage.setItem(key, JSON.stringify(data))
    },
    { detached: true } // the subscription lives as long as the store, not a component
  )
}

Compare it with the Vuex plugin:

Vuex plugin Pinia plugin
Runs once, for the whole store Runs once per store
Receives a list of rules (module, fields...) Reads the store's own persistence option (options)
Restores with store.replaceState Restores with store.$patch
Filters mutations by prefix ('session/') store.$subscribe already covers only that store

Register it in main.js:

// src/main.js
import { createPinia } from 'pinia'
import { persistence } from './stores/plugins/persistence.js'

const pinia = createPinia()
pinia.use(persistence)

app.use(pinia) // replaces app.use(createPinia())

There is no store with the persistence option yet, so nothing changes. The keys will be the same ones Vuex used (colmena-session and colmena-cache-bookings) and so will the format (the same fields), so anyone with an open session or a saved cache will not notice the migration. It is a detail that matters in a real migration: persisted data is a contract with previous versions of the application.

  1. Step 2: the bookings module → useBookingsStore

4.1 The store

Create src/stores/bookings.js, translating the Vuex module with the table in section 2:

// src/stores/bookings.js
// Bookings (Pinia, setup store): normalised, with optimistic cancellation and a persisted cache
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { useStore } from 'vuex' // TEMPORARY BRIDGE to the Vuex session (removed in step 3)
import { api } from '@/api'
import { durationHours, currentMonth } from '@/utils/dates.js'
import { useRoomsStore } from './rooms.js'

const byDateAndTime = (a, b) =>
  `${a.date} ${a.startTime}`.localeCompare(`${b.date} ${b.startTime}`)
const isActive = (booking) => booking.status !== 'cancelled'

export const useBookingsStore = defineStore(
  'bookings',
  () => {
    const roomsStore = useRoomsStore()
    const vuex = useStore() // TEMPORARY BRIDGE

    // --- State ---
    const byId = ref({})        // { [id]: booking }
    const ids = ref([])         // order of arrival
    const loading = ref(false)
    const error = ref(null)
    const operations = ref({})  // { [id]: 'cancelling' }

    // --- Getters (selectors) ---
    const bookings = computed(() => ids.value.map((id) => byId.value[id]))
    const bookingById = computed(() => (id) => byId.value[id] ?? null)
    const sortedBookings = computed(() => bookings.value.toSorted(byDateAndTime))
    const activeBookings = computed(() => sortedBookings.value.filter(isActive))

    const myBookings = computed(() => {
      if (vuex.getters['session/isManager']) return sortedBookings.value // TEMPORARY BRIDGE
      return sortedBookings.value.filter((b) => b.member === vuex.state.session.name)
    })

    const monthlyBookingsTotal = computed(() => {
      const month = currentMonth()
      return myBookings.value
        .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)
    })

    const isCancelling = computed(() => (id) => operations.value[id] === 'cancelling')

    // --- Internal functions (not returned: they are not public actions) ---
    // Replaces the saveBooking mutation: insert or replace
    function save(booking) {
      if (!(booking.id in byId.value)) ids.value.push(booking.id)
      byId.value[booking.id] = booking
    }

    // --- Actions ---
    let pendingLoad = null

    // Bookings and catalogue in parallel, without duplicate requests
    function loadBookings() {
      if (pendingLoad) return pendingLoad

      pendingLoad = (async () => {
        loading.value = true
        error.value = null
        try {
          const [list] = await Promise.all([api.bookings.fetchBookings(), roomsStore.loadRooms()])
          byId.value = Object.fromEntries(list.map((b) => [b.id, b]))
          ids.value = list.map((b) => b.id)
        } catch (e) {
          error.value = e.message
        } finally {
          loading.value = false
          pendingLoad = null
        }
      })()
      return pendingLoad
    }

    async function createBooking(data) {
      const created = await api.bookings.createBooking(data)
      save(created)
      return created
    }

    // Optimistic cancellation: reflected instantly and rolled back if the API fails
    async function cancelBooking(id) {
      const booking = byId.value[id]
      if (!booking || booking.status === 'cancelled' || operations.value[id]) return

      const previousStatus = booking.status
      operations.value[id] = 'cancelling'
      booking.status = 'cancelled'
      try {
        save(await api.bookings.cancelBooking(id)) // server version
      } catch (e) {
        if (byId.value[id]) byId.value[id].status = previousStatus // rollback
        throw e
      } finally {
        delete operations.value[id]
      }
    }

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

    return {
      byId, ids, loading, error, operations,
      bookings, bookingById, sortedBookings, activeBookings, myBookings, monthlyBookingsTotal, isCancelling,
      loadBookings, createBooking, cancelBooking, $reset
    }
  },
  {
    persistence: { storage: localStorage, key: 'colmena-cache-bookings', fields: ['byId', 'ids'] }
  }
)

Let's review the translation, which is almost mechanical:

  • State: each property of the Vuex state() is a ref with the same name. The views and the plugin will see the same fields.
  • Getters: each getter is a computed. Those that used rootGetters['rooms/...'] use roomsStore, and the chain of selectors (bookings → sortedBookings → activeBookings/myBookings → monthlyBookingsTotal) is kept identical.
  • Mutations: startLoading, setBookings, setError, setStatus, setOperation and clear disappear: their assignments are now inside the actions. saveBooking, which was used from two actions, becomes an internal function, save, which is not returned and is therefore not a public action.
  • Actions: no context and no commit. cancelBooking keeps its optimistic logic step by step: mark the operation, change the status, call the API, apply the server's version or roll back, and release the operation.
  • $reset replaces the clear mutation.
  • Persistence is declared in the third argument: the plugin from step 1 does the rest.
  • The bridge to Vuex: myBookings needs the session, which is still in Vuex. Pinia runs the stores' setup inside the application's context, so inject (and therefore Vuex's useStore(), which is an inject) works here. That way we avoid importing the Vuex store in this file, which would create a circular import (the Vuex session module is about to import this store).

4.2 Vuex dispatches to the Pinia store

The Vuex session module dispatched bookings/loadBookings and committed bookings/clear. Now it calls the Pinia store. In src/store/modules/session.js:

// src/store/modules/session.js
import { useBookingsStore } from '@/stores/bookings.js' // NEW

// In actions
async signIn({ commit }, { email, password }) {
  const member = await api.session.authenticate(email, password)
  commit('setMember', member)
  useBookingsStore().loadBookings() // before: dispatch('bookings/loadBookings', ..., { root: true })
},

signOut({ commit }) {
  commit('reset')
  useBookingsStore().$reset() // before: commit('bookings/clear', null, { root: true })
}

And remove the bookings module from Vuex. In src/store/index.js, the store is left with only session, and the bookings persistence rule disappears (the Pinia store declares it now):

// src/store/index.js
const PERSISTENCE_RULES = [
  { module: 'session', fields: ['name', 'email', 'plan', 'role'], storage: sessionStorage, key: 'colmena-session' }
]

// in createAppStore
modules: {
  session: createSessionModule(api)
},

Delete src/store/modules/bookings.js and its import.

4.3 The bookings components

DashboardBookingsView.vue is the view that uses the bookings the most. In its script, replace everything that came from Vuex:

// DashboardBookingsView.vue
import { ref, computed } from 'vue'
import { storeToRefs } from 'pinia'
import { useBookingsStore } from '@/stores/bookings.js'
import { useRoomsStore } from '@/stores/rooms.js'

const bookingsStore = useBookingsStore()
const roomsStore = useRoomsStore()

bookingsStore.loadBookings()

// The same names the template already used
const { loading, error, myBookings: bookings, monthlyBookingsTotal: monthTotal } = storeToRefs(bookingsStore)
const newBooking = computed(() => bookingsStore.bookingById(newBookingId.value))

function roomNameById(id) {
  return roomsStore.roomById(id)?.name ?? id
}

function isCancelling(id) {
  return bookingsStore.isCancelling(id)
}

const cancellationError = ref('')

async function cancel(booking) {
  if (!window.confirm(`Cancel the booking for the ${roomNameById(booking.roomId)} on ${booking.date}?`)) return
  cancellationError.value = ''
  try {
    await bookingsStore.cancelBooking(booking.id)
  } catch (e) {
    cancellationError.value = `Could not cancel the booking on ${booking.date}: ${e.message}. It has been restored.`
  }
}

The template does not change: storeToRefs with renaming (myBookings: bookings) keeps the names it already used. Remove the import of Vuex's useStore.

In BookingView.vue, replace the two lines that used Vuex for the bookings (the session stays in Vuex until step 3):

// BookingView.vue
import { useBookingsStore } from '@/stores/bookings.js'

const bookingsStore = useBookingsStore()
const bookingCount = computed(() => bookingsStore.activeBookings.length)

// In createBooking:
const created = await bookingsStore.createBooking(booking)

4.4 Checking step 2

  1. In DevTools, the Pinia panel now shows rooms and bookings; the Vuex one, only session.
  2. As Laura, open "My bookings", create and cancel bookings: everything works as before, including the optimistic cancellation (try it with ERROR_PROBABILITY = 1).
  3. Reload on "My bookings": the list appears instantly from colmena-cache-bookings, which is now written by the Pinia plugin.
  4. Sign out: the Pinia bookings store is emptied, because the Vuex session module calls its $reset().

  1. Step 3: the session module → useSessionStore

5.1 The store

Create src/stores/session.js:

// src/stores/session.js
// The member's session (Pinia, setup store), persisted in sessionStorage
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { api } from '@/api'
import { useBookingsStore } from './bookings.js'

export const useSessionStore = defineStore(
  'session',
  () => {
    // --- State: the usual model ---
    const name = ref('')
    const email = ref('')
    const plan = ref('flexible') // 'flexible' | 'fixed' | 'business'
    const role = ref('member')   // 'member' | 'manager'

    // --- Getters ---
    const active = computed(() => email.value !== '')
    const isManager = computed(() => active.value && role.value === 'manager')

    // --- Actions ---
    async function signIn(emailAddress, password) {
      const member = await api.session.authenticate(emailAddress, password) // throws if they are not valid
      name.value = member.name
      email.value = member.email
      plan.value = member.plan
      role.value = member.role
      useBookingsStore().loadBookings() // in the background, without await
    }

    function $reset() {
      name.value = ''
      email.value = ''
      plan.value = 'flexible'
      role.value = 'member'
    }

    function signOut() {
      $reset()
      useBookingsStore().$reset() // no data from the previous member must remain
    }

    return { name, email, plan, role, active, isManager, signIn, signOut, $reset }
  },
  {
    persistence: { storage: sessionStorage, key: 'colmena-session', fields: ['name', 'email', 'plan', 'role'] }
  }
)
  • signIn(emailAddress, password) gets back the two-argument signature that src/session.js had in 04-06: in Vuex they had to be grouped into an object because the payload is a single argument; in Pinia, an action is an ordinary function. The first parameter is called emailAddress so as not to shadow the store's email ref.
  • useBookingsStore() is called inside the actions, not at the top level of the setup. useBookingsStore uses useSessionStore (in myBookings, section 5.2) and vice versa: this is the circular dependency we warned about in 05-06. As long as at least one of the two calls the other inside a function, there is no problem. The two files import each other, which JavaScript modules allow as long as neither uses the other while it is still loading.

5.2 Removing the bridge from useBookingsStore

In src/stores/bookings.js, replace the bridge to Vuex with the session store:

// src/stores/bookings.js
// Remove: import { useStore } from 'vuex'  and  const vuex = useStore()
import { useSessionStore } from './session.js'

const myBookings = computed(() => {
  const session = useSessionStore() // inside the computed: avoids the circular problem in the setup
  if (session.isManager) return sortedBookings.value
  return sortedBookings.value.filter((b) => b.member === session.name)
})

5.3 The router guard

In src/router/index.js, remove import store from '@/store' and use the session store inside each guard:

// src/router/index.js
import { useSessionStore } from '@/stores/session.js'

// login route
beforeEnter: () => (useSessionStore().active ? { name: 'dashboard' } : true)

// Global guard
router.beforeEach((to) => {
  const session = useSessionStore()

  const requiresSession = to.matched.some((record) => record.meta.requiresSession)
  if (requiresSession && !session.active) {
    return { name: 'login', query: { redirect: to.fullPath } }
  }
  const requiredRole = to.meta.role
  if (requiredRole && session.role !== requiredRole) {
    return { name: 'dashboard-profile' }
  }
})

It is the same code as in 04-06, with session obtained from the store every time the guard runs. The first navigation is triggered by app.use(router), after app.use(pinia), so Pinia is already active. And because the persistence plugin restores the session when the store is created, the first guard already sees the session saved in sessionStorage.

5.4 The session components

The session store will be called session in every component. Because it has name, plan, role and active, the templates written in module 4 work exactly as they did.

AppHeader.vue:

// AppHeader.vue: replaces useStore, session and hasSession
import { useSessionStore } from '@/stores/session.js'

const session = useSessionStore()

async function onSignOut() {
  if (route.matched.some((record) => record.meta.requiresSession)) {
    const failure = await router.push({ name: 'home' })
    if (isNavigationFailure(failure)) return
  }
  session.signOut()
}
<!-- In the template: back to session.active -->
<template v-if="session.active">

DashboardView.vue and DashboardProfileView.vue: replace useStore and the session computed with:

import { useSessionStore } from '@/stores/session.js'

const session = useSessionStore()

LoginView.vue:

// LoginView.vue: replaces useStore
import { useSessionStore } from '@/stores/session.js'

const session = useSessionStore()

// In submit():
await session.signIn(email.value, password.value)

BookingView.vue: the prop that BookingForm receives is now the store itself, which is a reactive object with name and role:

// BookingView.vue: replaces useStore and the session computed
import { useSessionStore } from '@/stores/session.js'

const session = useSessionStore()
<BookingForm ... :session="session" />  <!-- no changes to the template -->

BookingForm does not change: it is still a presentational component that receives the session as a prop (05-04). It does not even know that the state library has changed.

  1. Step 4: removing Vuex

After step 3, the Vuex store has no useful module left. Check that nothing uses it:

# None of these searches should return results in src/ (except src/store/, which we are about to delete)
grep -rn "from 'vuex'" src
grep -rn "\$store\|useStore()" src
grep -rn "@/store'" src

Then:

npm uninstall vuex

Delete the whole src/store/ folder (index.js, modules/session.js and plugins/persistence.js). And leave main.js like this:

// src/main.js
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import { persistence } from './stores/plugins/persistence.js'
import { CONFIG_KEY } from './keys.js'
import './assets/main.css'

const app = createApp(App)

app.config.errorHandler = (error, instance, info) => {
  // ... unchanged ...
}

app.provide(CONFIG_KEY, { centreName: 'Coworking Colmena', openingHour: 8, closingHour: 20 })

const pinia = createPinia()
pinia.use(persistence)

app.use(pinia)  // first: the router uses the stores in its guards
app.use(router)

app.mount('#app')

Colmena's state management structure ends up like this:

src/
├── api/
│   ├── index.js          ← facade: api.rooms, api.bookings, api.session
│   ├── simulation.js     ← wait, randomDelay, failSometimes, errorWithStatus
│   ├── rooms.js          ← fetchRooms, fetchRoom
│   ├── bookings.js       ← fetchBookings, createBooking, cancelBooking
│   └── session.js        ← authenticate
├── stores/
│   ├── rooms.js          ← useRoomsStore
│   ├── bookings.js       ← useBookingsStore
│   ├── session.js        ← useSessionStore
│   └── plugins/
│       └── persistence.js
└── utils/
    └── dates.js          ← toMinutes, durationHours, toISODate, dateInDays, currentMonth

src/store/, src/session.js and the session and bookings provide calls have gone. Only CONFIG_KEY remains in src/keys.js.

  1. Checklist and typical risks

7.1 Final checklist

Before considering a migration finished, go through this list (applied here to Colmena):

Check How
No reference to Vuex remains The searches in section 6; vuex does not appear in package.json
Each module has its store with the same behaviour Repeat the "Try it" sections from lessons 05-02 to 05-06: loading, caching, errors, overlaps, optimistic cancellation and its rollback
The guards work, including on reload Reload on /dashboard/bookings with a session; open /dashboard/invoices as a member; open /book/basement
Persisted data is still compatible A session opened before the migration is still open afterwards; the bookings cache is read
No destructuring without storeToRefs Search for = use followed by { on the same line (const { ... } = useXStore())
No useXStore() at the top level of a module that is not a component or a store Review src/router/ and any service
All the state is returned in the setup stores Compare each store's refs with its return and with the DevTools inspector
The setup stores that need it have $reset useRoomsStore, useBookingsStore, useSessionStore
The production build works npm run build with no new errors or warnings

7.2 Typical risks

Risk Symptom Prevention
Destructuring the store A value does not update on screen storeToRefs for state and getters
useXStore() out of context getActivePinia() was called but there was no active Pinia Call it inside functions; install Pinia before the router
Circular dependencies between stores A store is undefined or never gets created Call the other store inside getters or actions, not at the top level of the setup
Forgetting to return state It does not appear in DevTools; the plugin does not persist it; it fails in SSR Review the return of each setup store
Losing the discipline of mutations Components writing the state any old way; logic scattered around Agree as a team: changes that involve logic always go in actions
Changing the format of persisted data Users with a "broken" session after deployment Keep the keys and fields, or write a conversion when restoring
Leaving Vuex helpers with Pinia imports (or vice versa) Errors in Options API components Review the imports of mapState, mapActions...
Vuex packages with no equivalent (vuex-persistedstate, vuex-router-sync...) Functionality silently lost Inventory them at the start and decide on their replacement
Tests that created Vuex stores They fail after the migration Migrate them in the same step as their module (08-03)
Temporary bridges that stay Hybrid code that is hard to understand months later Label each bridge (like our TEMPORARY BRIDGE comments) and remove it in the next step

  1. The public API of Colmena's stores

From here on, the course will use only these three stores. This is their final public API:

useRoomsStore() — src/stores/rooms.js (id 'rooms')

Type Name Description
State rooms Array with the complete catalogue ({ id, name, floor, capacity, hourlyPrice, equipment, available })
State loadedAt Timestamp (Date.now()) of the last successful load, or null
State loading true while the catalogue is being requested
State error Message from the last loading error, or null
State catalogView Preferred catalogue view: 'grid', 'table' or 'map' (writable)
Getter availableRooms Rooms with available: true
Getter roomById(id) The room with that id, or undefined
Action loadRooms({ force = false } = {}) Loads the catalogue if there is no fresh copy (5 minutes) or if force; reuses the request in progress; never rejects (the error is left in error)
Action $reset() Returns to the initial state

useBookingsStore() — src/stores/bookings.js (id 'bookings')

Type Name Description
State byId An object { [id]: booking } (normalised state; persisted in localStorage)
State ids Array of ids in order of arrival (persisted)
State loading true while the bookings are being requested
State error Message from the last loading error, or null
State operations An object { [id]: 'cancelling' } with the operations in progress
Getter bookings All the bookings, in order of arrival
Getter bookingById(id) The booking with that id, or null
Getter sortedBookings All of them, by date and start time
Getter activeBookings Those not cancelled, sorted
Getter myBookings The signed-in member's (in any status), sorted; a manager sees all of them
Getter monthlyBookingsTotal Amount (€) of the active myBookings in the current month, based on each room's hourlyPrice
Getter isCancelling(id) true if that booking is being cancelled
Action loadBookings() Requests the bookings (and the catalogue, in parallel); reuses the request in progress; never rejects
Action createBooking(data) Creates the booking in the API and adds it; returns the created booking (with the server's id); rejects with the API's error (connection, 404, 409 for an overlap, 422)
Action cancelBooking(id) Optimistic cancellation; rejects after rolling back if the API fails
Action $reset() Empties the store (called by signOut)

useSessionStore() — src/stores/session.js (id 'session')

Type Name Description
State name The member's name ('' with no session)
State email The member's email address ('' with no session)
State plan 'flexible', 'fixed' or 'business'
State role 'member' or 'manager'
Getter active true if there is a signed-in session
Getter isManager true if there is a session and the role is 'manager'
Action signIn(email, password) Authenticates (demo accounts, password "colmena"), stores the member and starts loading the bookings; rejects with "Incorrect email or password"
Action signOut() Clears the session and empties the bookings store
Action $reset() Returns to the no-session state

The session state is persisted in sessionStorage (key colmena-session) by the persistence plugin, which reads the persistence option from the third argument of defineStore. The data layer the stores use is src/api/index.js (api.rooms, api.bookings, api.session).

A usage convention for the rest of the course: in components, const roomsStore = useRoomsStore(), const bookingsStore = useBookingsStore() and const session = useSessionStore(); to destructure state or getters, storeToRefs.

Common Mistakes and Tips

  • Migrating everything in one go. It multiplies the risk and makes bugs impossible to pin down. One module at a time, with the application working after every step.
  • Translating mutations into public actions one by one. Most mutations were simple assignments that should disappear into the actions. Only those that are reused deserve an internal function.
  • Changing the public API during the migration (action names, data shapes). It mixes two changes into one. Migrate first with the same interface and improve afterwards.
  • Forgetting about persisted data. Changing the key or the format breaks users' open sessions.
  • Importing a store at the top level of the setup of another store that in turn imports it. Call it inside a computed or an action.
  • Leaving Vuex's useStore in a component after removing its module: it fails at runtime, not at build time. The searches in section 6 catch it.
  • Tip: mark each temporary bridge with a recognisable comment (TEMPORARY BRIDGE) and search for it when you finish: none should survive the migration.
  • Tip: if the project has many Options API components, migrate the stores first and leave the components with Pinia's map* helpers; rewriting them in <script setup> is a separate task, which can be done later.

Exercises

Exercise 1. Migrate this Vuex module from a legacy application to Pinia, as a setup store, keeping its public API (apart from commit/dispatch). State which mutations disappear.

export default {
  namespaced: true,
  state: () => ({ notifications: [], nextId: 1 }),
  getters: {
    hasNotifications: (state) => state.notifications.length > 0,
    lastNotification: (state) => state.notifications.at(-1) ?? null
  },
  mutations: {
    add(state, text) {
      state.notifications.push({ id: state.nextId++, text })
    },
    remove(state, id) {
      state.notifications = state.notifications.filter((n) => n.id !== id)
    }
  },
  actions: {
    notify({ commit, state }, { text, duration = 4000 }) {
      const id = state.nextId
      commit('add', text)
      setTimeout(() => commit('remove', id), duration)
    }
  }
}

Exercise 2. Create a small useNotificationsStore store in Colmena (based on the previous solution) and use it to show temporary notifications in App.vue when a booking is created or cancelled. Do it without touching useBookingsStore: use $onAction from App.vue.

Exercise 3. A colleague has finished a migration and the application shows "Incorrect email or password" correctly, but after signing in the header keeps showing "Sign in" until the page is reloaded. This is their code. Find the bug and explain why reloading "fixes it".

// AppHeader.vue
import { useSessionStore } from '@/stores/session.js'
const { active, name, signOut } = useSessionStore()

Solutions

Solution 1.

// src/stores/notifications.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useNotificationsStore = defineStore('notifications', () => {
  const notifications = ref([])
  const nextId = ref(1)

  const hasNotifications = computed(() => notifications.value.length > 0)
  const lastNotification = computed(() => notifications.value.at(-1) ?? null)

  function remove(id) {
    notifications.value = notifications.value.filter((n) => n.id !== id)
  }

  function notify({ text, duration = 4000 }) {
    const id = nextId.value++
    notifications.value.push({ id, text })
    setTimeout(() => remove(id), duration)
  }

  function $reset() {
    notifications.value = []
    nextId.value = 1
  }

  return { notifications, nextId, hasNotifications, lastNotification, notify, remove, $reset }
})

The add mutation disappears: its code moves into notify, the only one that used it. remove is kept as a public action, because as well as being used from notify it makes sense to call it from outside (a "Close" button on the notification); in Vuex, the component would have had to commit the mutation directly. nextId is still state (and is returned), because it was state in the original. You could keep the notify({ text, duration }) signature or simplify it to notify(text, duration): in a migration, keeping the signature avoids having to change every call site at the same time.

Solution 2.

<!-- App.vue -->
<script setup>
import AppHeader from './components/AppHeader.vue'
import { useBookingsStore } from './stores/bookings.js'
import { useNotificationsStore } from './stores/notifications.js'

const notificationsStore = useNotificationsStore()

useBookingsStore().$onAction(({ name, after }) => {
  after(() => {
    if (name === 'createBooking') notificationsStore.notify({ text: 'Booking created' })
    if (name === 'cancelBooking') notificationsStore.notify({ text: 'Booking cancelled' })
  })
})
</script>

<template>
  <AppHeader />
  <main class="content"><RouterView /></main>

  <div class="notifications" role="status" aria-live="polite">
    <p v-for="notification in notificationsStore.notifications" :key="notification.id" class="note">
      {{ notification.text }}
      <button type="button" aria-label="Close notification" @click="notificationsStore.remove(notification.id)">×</button>
    </p>
  </div>
</template>

<style scoped>
.notifications {
  position: fixed;
  right: 1rem;
  bottom: 1rem;
  display: grid;
  gap: 0.5rem;
}
</style>

after only runs if the action finishes successfully (including its promise), so a cancellation that fails and is rolled back does not show "Booking cancelled". Because $onAction is registered inside App's setup, it would be unsubscribed if App were unmounted (which never happens). useBookingsStore knows nothing about the notifications: the coupling goes in one direction only. Compare this with exercise 3 in 03-07, which solved the same problem with provide.

Solution 3. They destructure the store without storeToRefs: active and name are copies of the values they had when the header was created (false and ''). When signIn changes the state, those variables do not notice. On reload, the persistence plugin restores the session before the header is created, so the copies start out with the right values: that is why it "fixes itself". The signOut action does work, because actions can be destructured. The fix:

import { storeToRefs } from 'pinia'
import { useSessionStore } from '@/stores/session.js'

const session = useSessionStore()
const { active, name } = storeToRefs(session)
const { signOut } = session

Or, more simply and consistently with the rest of Colmena, use session.active and session.name directly in the template.

Conclusion

You have completed a real migration from Vuex to Pinia with an incremental strategy: Pinia and Vuex coexist, you migrate one module at a time following the dependency graph (from the most independent to the most delicate), temporary bridges connect the two libraries in the meantime and the application works after every step. The mapping table guides the translation: modules become stores with an id, state becomes ref, getters become computed, mutations disappear into the actions, commit and dispatch give way to direct assignments and calls, rootState/rootGetters to using other stores, the map* helpers to storeToRefs or to Pinia's mapStores/mapState/mapActions, and Vuex plugins to Pinia plugins that run per store. In Colmena you have migrated the persistence plugin, the bookings module to useBookingsStore (normalised, with optimistic cancellation and a persisted cache) and the session module to useSessionStore (with the router guard), you have updated the components, uninstalled Vuex and documented the public API of useRoomsStore, useBookingsStore and useSessionStore.

With this you close the state management module, and the architecture of Colmena Bookings is finally complete: the data layer in src/api/, the shared state in three Pinia stores with their rules, their debugging tools and their persistence, the router checking the session in its guards, and components that confine themselves to displaying data and dispatching actions. The temporary solutions from module 4 have disappeared without a trace. From now on we will focus on the presentation layer again, which still has a few pieces that need polishing: templates with conditions and loops that can be expressed better, a form that does not put the focus where it should, and a menu that does not close when you click outside it. We will start by taking an in-depth look at the tools Vue ships with for markup in Built-in Directives.

New edition · October 2026

Vue.js Course

Module 1: Introduction to Vue.js

Module 2: Vue.js Basics

Module 3: Vue.js Components

Module 4: Vue Router

Module 5: State Management with Vuex and Pinia

Module 6: Vue.js Directives

Module 7: Vue.js Plugins

Module 8: Testing in Vue.js

Module 9: Advanced Vue.js Concepts

Module 10: Building and Deploying Vue.js Applications

Module 11: Real-World Vue.js Projects

© Copyright 2026. All rights reserved