With all its views connected to the store, Colmena works, but if you use it carefully, problems appear that are not about Vuex itself, but about how a store is organised as it grows: cancelling a booking takes more than a second to show, signing in and opening the dashboard requests the bookings twice, finding a booking by its id goes through the whole list, the session's persistence is mixed in with its actions, and the modules import the real API directly, which will make them hard to test. In this lesson you will see the patterns with which professional Vuex applications solve these problems: normalising the state, composing getters as selectors, coordinating complex asynchronous actions (parallel requests, duplicate requests, per-entity state, optimistic updates), separating data access with the repository pattern, and extending the store with plugins. These are patterns you will find in legacy code and which, as you will see in the next few lessons, remain valid with Pinia.

  1. Normalising the state

1.1 The problem with lists

Today, the bookings are an array: state.list = [{ id: 'r-1', ... }, { id: 'r-2', ... }]. To find a booking you have to go through it (find, findIndex), and that happens on every update, every cancellation and every lookup for the "new booking" notice. With three bookings it makes no difference; with thousands, in a management dashboard, you notice it. And there is a subtler problem: if the same booking appeared in two lists (the member's and a room's), there would be two copies to keep in sync.

1.2 Normalised state: byId + ids

Normalising means storing the entities as in a database table: an object indexed by id containing each entity only once, plus an array of ids that preserves the order:

// List (denormalised)
list: [
  { id: 'r-1', roomId: 'polen', status: 'confirmed' /* ... */ },
  { id: 'r-2', roomId: 'nectar', status: 'pending' /* ... */ }
]

// Normalised
byId: {
  'r-1': { id: 'r-1', roomId: 'polen', status: 'confirmed' /* ... */ },
  'r-2': { id: 'r-2', roomId: 'nectar', status: 'pending' /* ... */ }
},
ids: ['r-1', 'r-2']
Operation With a list Normalised
Find by id list.find(...): iterates byId[id]: direct access
Update an entity findIndex + assign byId[id] = updated
Add push byId[id] = b + ids.push(id)
Check whether it exists some(...) id in byId
Iterate in order Directly ids.map((id) => byId[id]) (in a getter)
Several "lists" of the same entity Duplicate copies Several arrays of ids, a single copy of each entity

The price is that reading "the list" takes one more step, which is solved with a getter. We will see it in the case study.

1.3 When to normalise

  • Yes: large collections, entities that are often updated individually, entities referenced from several places (a booking that appears in the member's dashboard, in the room's calendar and in a report).
  • No: small, almost static collections. Colmena's catalogue has five rooms that do not change during the session: we will leave it as a list.

  1. Getters as composable selectors

In the Redux ecosystem, the functions that extract and derive data from the state are called selectors. Vuex getters play that role, and their real power appears when they are composed: each getter does one thing only and builds on others.

flowchart LR
    E["state.byId + state.ids"] --> R["bookings<br/>(list in order)"]
    R --> O["sortedBookings<br/>(by date and time)"]
    O --> A["activeBookings<br/>(not cancelled)"]
    O --> M["myBookings<br/>(the member's;<br/>all of them for a manager)"]
    S["rootState.session<br/>rootGetters['session/isManager']"] --> M
    M --> I["monthlyBookingsTotal"]
    P["rootGetters['rooms/roomById']"] --> I

Advantages of this chain:

  • Each rule is in a single place. "Active" means "not cancelled" in activeBookings and nowhere else; the order by date, in sortedBookings.
  • A chained cache. If the session changes, myBookings is recalculated, but sortedBookings is not: its result is still cached.
  • Simpler components. DashboardBookingsView sorted the bookings with its own computed property; now it reads myBookings, already sorted.

Rules for writing good selectors:

Rule Why
One getter, one transformation They can be combined and tested separately
Start from the nearest getter, not from the state You reuse the cache and the rules of the previous ones
Return new arrays (filter, toSorted), never sort the original The state is not modified from a getter
Getters with arguments only for one-off lookups They have no cache (05-02)
Names that express what they return, not how myBookings, not bookingsFilteredByName

  1. Complex asynchronous actions

3.1 Orchestrating several requests

loadBookings first dispatches rooms/loadRooms, waits for it and then requests the bookings. But neither request depends on the result of the other: they can run in parallel.

// In series: the total time is the SUM of the two
await dispatch('rooms/loadRooms', undefined, { root: true })
const bookings = await api.bookings.fetchBookings()

// In parallel: the total time is that of the SLOWEST
const [bookings] = await Promise.all([
  api.bookings.fetchBookings(),
  dispatch('rooms/loadRooms', undefined, { root: true })
])
Tool Behaviour When
await one after another In series When a request needs the result of the previous one
Promise.all([...]) In parallel; rejects as soon as one fails When you need all of them to continue
Promise.allSettled([...]) In parallel; waits for all of them and tells you which failed When each result is useful on its own (a dashboard with several independent blocks)

In Colmena, loadRooms never rejects (it stores its error in the state), so Promise.all will only fail if the bookings fail.

3.2 Avoiding duplicate requests

On signing in, the session/signIn action dispatches bookings/loadBookings; a moment later, DashboardBookingsView is mounted and dispatches it again. Two identical requests in flight: pointless traffic and, worse, whichever arrives last decides the state, even if it is the older one.

The solution is to share the promise of the request in progress:

let pendingLoad = null // outside the state: a promise is not serialisable

async loadBookings({ commit }) {
  if (pendingLoad) return pendingLoad // one is already under way: we reuse it

  pendingLoad = (async () => {
    commit('startLoading')
    try {
      commit('setBookings', await api.bookings.fetchBookings())
    } catch (error) {
      commit('setError', error.message)
    } finally {
      pendingLoad = null // the next call will make a new request
    }
  })()

  return pendingLoad
}
  • The promise lives outside the state (in a module variable), because the state must be serialisable and because it is not data to be displayed.
  • Whoever arrives late receives the same promise and waits for the same result.
  • finally releases it, whether it went well or failed.

This is different from the catalogue's cache (loadedAt): the cache avoids requesting something you already have; deduplication avoids requesting twice something that is being requested. The catalogue needs both.

3.3 Per-entity request state

A single loading works for loading a collection, but not for operations on specific items: if the user cancels two bookings in a row, which button should show "Cancelling…"? In 05-04 we solved it with a local ref in the view, which has two limitations: it only allows one operation at a time, and no other screen knows that the booking is being cancelled.

The pattern is to store an id → operation in progress map in the state:

state: () => ({
  // ...
  operations: {} // { 'r-1': 'cancelling' }
}),
mutations: {
  setOperation(state, { id, operation }) {
    if (operation) state.operations[id] = operation
    else delete state.operations[id]
  }
},
getters: {
  isCancelling: (state) => (id) => state.operations[id] === 'cancelling'
}

That way, any component can disable the buttons for that booking, and the action can refuse to cancel the same one twice.

3.4 Optimistic update with rollback

When the user cancels a booking, the interface waits for the API's response (up to 1.5 seconds in the simulation) before reflecting the change. An optimistic update reverses the order: the change is applied immediately, on the assumption that the API will accept it, and if it fails, it is rolled back.

sequenceDiagram
    participant V as View
    participant A as cancelBooking action
    participant E as State
    participant API
    V->>A: dispatch('bookings/cancelBooking', id)
    A->>E: setOperation(cancelling)<br/>setStatus(cancelled)
    Note over V,E: The interface shows "cancelled" instantly
    A->>API: cancelBooking(id)
    alt The API responds successfully
        API-->>A: updated booking
        A->>E: saveBooking(server version)
    else The API fails
        API-->>A: error
        A->>E: setStatus(previous status)
        A-->>V: rethrows the error (the view warns the user)
    end
    A->>E: setOperation(null)

Keys to doing it well:

  • Keep what you need to roll back before the change (the booking's previous status).
  • After success, apply the server's version: it may bring data the client did not know about (a cancellation date, a calculated refund).
  • After failure, roll back and tell the user. A change that "undoes itself" without explanation is disconcerting: the view must show that the cancellation failed.
  • Use it only when success is the norm and the change is easy to roll back. For operations whose effects are hard to undo in the user's eyes (a payment), it is better to wait for confirmation.
Pessimistic (wait) Optimistic
Perceived response Slow: waits for the network Immediate
Complexity Low You have to roll back and warn the user
If it fails Nothing to undo The user sees the change and then its rollback
Suitable for Payments, creations with server data Cancelling, marking, sorting, "likes"

  1. The repository pattern: a swappable API layer

Colmena's modules import the functions from src/api/ directly:

import { fetchBookings } from '@/api/bookings.js'

That couples them to the real API. To test a module (08-03), you would have to intercept those imports. The repository pattern separates the what (fetching bookings) from the how (with fetch, with the simulation, with test data): the store depends on an object with a known interface, and whoever creates the store decides which implementation to pass it.

flowchart LR
    S["Store modules"] -->|"api.bookings.fetchBookings()"| I["Interface: api object"]
    I --> R["Current simulation<br/>(src/api/*.js)"]
    I -.-> F["Real HTTP API<br/>(in the future)"]
    I -.-> P["Test data<br/>(in the tests)"]

In Vuex it is applied by turning each module into a factory that receives the API:

// Before: export default { namespaced: true, ... }
// After:
export function createBookingsModule(api) {
  return {
    namespaced: true,
    // ... the actions use api.bookings.fetchBookings(), api.bookings.createBooking()...
  }
}

And the store, into a factory that receives the API with a default value:

export function createAppStore({ api = colmenaApi } = {}) {
  return createStore({
    modules: { bookings: createBookingsModule(api) /* ... */ }
  })
}

export default createAppStore() // the application uses the default API

In a test, createAppStore({ api: fakeApi }) will be enough, without touching any module. And if Colmena gets a real server tomorrow, you change the implementation of src/api/ without touching the store.

  1. Vuex plugins

5.1 What a Vuex plugin is

A Vuex plugin is a function that receives the store when it is created. It is registered with the plugins option and usually uses two subscription methods:

function myPlugin(store) {
  // Runs once, when the store is created

  store.subscribe((mutation, state) => {
    // After EVERY mutation: mutation = { type, payload }, state = the already-modified state
  })

  store.subscribeAction((action, state) => {
    // Before each action: action = { type, payload }
  })
}

const store = createStore({
  // ...
  plugins: [myPlugin]
})
Method When it notifies Typical use
store.subscribe(fn) After each mutation Persistence, syncing with another tab, logging
store.subscribeAction(fn) or { before, after, error } Before (or after, or on failure of) each action Analytics, measuring timings, reporting errors
store.watch(getter, fn) When a value calculated from the state changes Reacting to a specific piece of data
store.replaceState(state) — Replacing the whole state (restoring saved data)

All the subscription methods return a function for unsubscribing. Plugins must not modify the state directly: if they need to change it, they commit mutations like any other code.

5.2 Persistence with store.subscribe

Persistence is the most common plugin: saving part of the state to localStorage (or sessionStorage) and restoring it on reload. Today, the session module does it by hand: it reads sessionStorage in its state() and writes in its actions. A plugin moves this out of the module and makes it declarative: a list of rules says which module, which fields, in which storage and under which key.

// src/store/plugins/persistence.js
// Saves and restores fields of store modules in localStorage or sessionStorage.
// rules: [{ module, fields, storage, key }]
export function createPersistence(rules) {
  return (store) => {
    // 1. When the store is created: restore what was saved
    const state = { ...store.state }
    for (const { module, storage, key } of rules) {
      try {
        const saved = JSON.parse(storage.getItem(key))
        if (saved) state[module] = { ...store.state[module], ...saved }
      } catch {
        storage.removeItem(key) // corrupted data: discarded
      }
    }
    store.replaceState(state)

    // 2. After each mutation of a module that has a rule: save its fields
    store.subscribe((mutation, currentState) => {
      for (const { module, fields, storage, key } of rules) {
        if (!mutation.type.startsWith(`${module}/`)) continue
        const data = Object.fromEntries(fields.map((field) => [field, currentState[module][field]]))
        storage.setItem(key, JSON.stringify(data))
      }
    })
  }
}
  • Restoring with replaceState: it builds a new state by combining each module's initial state with what was saved, and replaces it in one go. When combining ({ ...initial, ...saved }), any new properties that were not saved keep their initial value.
  • Only the specified fields: never loading, error or operations, which make no sense to restore.
  • mutation.type.startsWith('session/'): the namespace tells you which module each mutation belongs to.
  • Watch out for size and frequency: JSON.stringify on every mutation is cheap with small states. With large states or very frequent mutations, it is worth batching the writes (waiting a few milliseconds without changes before saving).

In legacy code you will often see the vuex-persistedstate package, which does exactly this with more options. It is no longer maintained, and in a migration to Pinia you will have to replace it; understanding how it works inside, as you have just done, makes that replacement easier.

5.3 createLogger in development

Vuex includes a plugin that writes every mutation to the console, with the previous and next state, as well as every action:

import { createStore, createLogger } from 'vuex'

const store = createStore({
  // ...
  plugins: import.meta.env.DEV ? [createLogger({ collapsed: true })] : []
})
  • Development only: to show the previous and next state, it makes a deep copy of the state on every mutation. In production it would be a pointless cost (and it would fill the user's console).
  • Useful options: collapsed (collapsed groups), filter(mutation, stateBefore, stateAfter) to log only some of them, logActions: false to leave out the actions.
  • It is useful when DevTools is not available (a browser without the extension, a mobile device with remote console debugging).

  1. Strict mode, in development only

We enabled it in 05-02 with strict: import.meta.env.DEV. With the patterns in this lesson, it is worth remembering why that condition matters:

  • Strict mode watches the whole state tree deeply. With normalised bookings, a persisted cache and per-entity operations, the tree grows and watching it costs more.
  • Plugins are not exempt: if a plugin modified the state outside a mutation, strict mode would detect it. replaceState is allowed, because Vuex internally treats it as an authorised change.
  • In production (npm run build), import.meta.env.DEV is false and Vite even removes the code that depends on it.

  1. When to apply each pattern

Pattern Apply it when... Not needed when...
Normalisation (byId + ids) Large collections, frequent individual updates, entities referenced from several places Small, static lists (the five-room catalogue)
Composable selectors Several screens derive similar data A single trivial use
Parallel requests Several independent requests before showing something One request needs the result of another
Request deduplication The same load can be triggered from several places at once A single view triggers each load
Per-entity request state Operations on specific items that other parts need to know about One global operation at a time
Optimistic update Operations that almost always succeed and are easy to roll back Payments, irreversible operations or ones with data only the server knows
Repository (injected API) The store is going to be tested or the data source may change Throwaway prototypes
Persistence plugin Data that must survive a reload on the client Data already persisted on the server that reloads quickly
createLogger Debugging without DevTools Production

  1. Case study: normalised bookings, optimistic cancellation and persistence

8.1 The API facade

Create src/api/index.js, which brings the three APIs together in a single object with a known shape:

// src/api/index.js
// Facade for the data layer: the store depends on this object, not on the specific files
import * as rooms from './rooms.js'
import * as bookings from './bookings.js'
import * as session from './session.js'

export const api = { rooms, bookings, session }
// api.rooms.fetchRooms(), api.bookings.createBooking(data), api.session.authenticate(email, password)...

import * as rooms gathers all of a file's exports into an object. The internal functions (readTable, overlap...) are not exported, so they are not part of the interface.

8.2 The rooms module, as a factory and without duplicate requests

// src/store/modules/rooms.js
const CATALOG_MAX_AGE_MS = 5 * 60 * 1000

export function createRoomsModule(api) {
  let pendingLoad = null

  return {
    namespaced: true,

    state: () => ({
      list: [],
      loadedAt: null,
      loading: false,
      error: null,
      catalogView: 'grid'
    }),

    getters: {
      availableRooms: (state) => state.list.filter((room) => room.available),
      roomById: (state) => (id) => state.list.find((room) => room.id === id)
    },

    mutations: {
      // startLoading, setRooms, setError and setCatalogView: unchanged
    },

    actions: {
      loadRooms({ state, commit }, { force = false } = {}) {
        const fresh = state.loadedAt !== null && Date.now() - state.loadedAt < CATALOG_MAX_AGE_MS
        if (fresh && !force) return Promise.resolve()
        if (pendingLoad) return pendingLoad

        pendingLoad = (async () => {
          commit('startLoading')
          try {
            commit('setRooms', await api.rooms.fetchRooms())
          } catch (error) {
            commit('setError', error.message)
          } finally {
            pendingLoad = null
          }
        })()
        return pendingLoad
      }
    }
  }
}

The catalogue is not normalised (section 1.3). What is new is the factory (api as a parameter, api.rooms.fetchRooms()) and the deduplication: if HomeView and DashboardBookingsView request the catalogue at the same time, only one request goes out.

8.3 The bookings module, normalised

Replace src/store/modules/bookings.js completely:

// src/store/modules/bookings.js
import { durationHours, currentMonth } from '@/utils/dates.js'

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

export function createBookingsModule(api) {
  let pendingLoad = null

  return {
    namespaced: true,

    state: () => ({
      byId: {},        // { [id]: booking }: each booking, only once
      ids: [],         // order of arrival
      loading: false,
      error: null,
      operations: {}   // { [id]: 'cancelling' }: operations in progress per booking
    }),

    getters: {
      // --- Basic selectors ---
      bookings: (state) => state.ids.map((id) => state.byId[id]),
      bookingById: (state) => (id) => state.byId[id] ?? null,

      // --- Composed selectors ---
      sortedBookings: (state, getters) => getters.bookings.toSorted(byDateAndTime),
      activeBookings: (state, getters) => getters.sortedBookings.filter(isActive),

      // The signed-in member's bookings (in any status); a manager sees all of them
      myBookings(state, getters, rootState, rootGetters) {
        if (rootGetters['session/isManager']) return getters.sortedBookings
        return getters.sortedBookings.filter((b) => b.member === rootState.session.name)
      },

      // Amount for MY active bookings in the current month
      monthlyBookingsTotal(state, getters, rootState, rootGetters) {
        const month = currentMonth()
        return getters.myBookings
          .filter((b) => isActive(b) && b.date.startsWith(month))
          .reduce((total, b) => {
            const room = rootGetters['rooms/roomById'](b.roomId)
            return room ? total + room.hourlyPrice * durationHours(b.startTime, b.endTime) : total
          }, 0)
      },

      isCancelling: (state) => (id) => state.operations[id] === 'cancelling'
    },

    mutations: {
      startLoading(state) {
        state.loading = true
        state.error = null
      },
      setBookings(state, bookings) {
        state.byId = Object.fromEntries(bookings.map((b) => [b.id, b]))
        state.ids = bookings.map((b) => b.id)
        state.loading = false
      },
      setError(state, message) {
        state.error = message
        state.loading = false
      },
      // Inserts or replaces (replaces addBooking and updateBooking)
      saveBooking(state, booking) {
        if (!(booking.id in state.byId)) state.ids.push(booking.id)
        state.byId[booking.id] = booking
      },
      setStatus(state, { id, status }) {
        if (state.byId[id]) state.byId[id].status = status
      },
      setOperation(state, { id, operation }) {
        if (operation) state.operations[id] = operation
        else delete state.operations[id]
      },
      clear(state) {
        state.byId = {}
        state.ids = []
        state.error = null
        state.operations = {}
      }
    },

    actions: {
      // Bookings and catalogue in parallel, without duplicate requests
      loadBookings({ commit, dispatch }) {
        if (pendingLoad) return pendingLoad

        pendingLoad = (async () => {
          commit('startLoading')
          try {
            const [bookings] = await Promise.all([
              api.bookings.fetchBookings(),
              dispatch('rooms/loadRooms', undefined, { root: true })
            ])
            commit('setBookings', bookings)
          } catch (error) {
            commit('setError', error.message)
          } finally {
            pendingLoad = null
          }
        })()
        return pendingLoad
      },

      async createBooking({ commit }, data) {
        const created = await api.bookings.createBooking(data)
        commit('saveBooking', created)
        return created
      },

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

        const previousStatus = booking.status
        commit('setOperation', { id, operation: 'cancelling' })
        commit('setStatus', { id, status: 'cancelled' })
        try {
          commit('saveBooking', await api.bookings.cancelBooking(id)) // server version
        } catch (error) {
          commit('setStatus', { id, status: previousStatus }) // rollback
          throw error
        } finally {
          commit('setOperation', { id, operation: null })
        }
      }
    }
  }
}

The points worth pausing over:

  • setBookings normalises the API's response (which is still an array) with Object.fromEntries. The API does not change: normalising is a decision on the client's side.
  • saveBooking is an "insert or replace" operation (an upsert): it serves both for creating and for updating. The addBooking and updateBooking mutations disappear.
  • myBookings filters by the member's name, as in exercise 2 of 05-03, but it includes the cancelled ones: the dashboard shows them with their badge.
  • monthlyBookingsTotal now builds on myBookings: in "My bookings", the amount is the member's. The change of rule is in a single place.
  • cancelBooking ignores repeated requests (state.operations[id]) and bookings that are already cancelled. And it rethrows the error after rolling back: it is a user command and the view must warn the user.

8.4 The session module, with no persistence of its own

Persistence leaves the module: the plugin will handle it.

// src/store/modules/session.js
export function createEmptySession() {
  return { name: '', email: '', plan: 'flexible', role: 'member' }
}

export function createSessionModule(api) {
  return {
    namespaced: true,

    state: () => createEmptySession(),

    getters: {
      active: (state) => state.email !== '',
      isManager: (state, getters) => getters.active && state.role === 'manager'
    },

    mutations: {
      setMember(state, { name, email, plan, role }) {
        Object.assign(state, { name, email, plan, role })
      },
      reset(state) {
        Object.assign(state, createEmptySession())
      }
    },

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

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

Compare it with the version in 05-03: STORAGE_KEY, readSavedSession and the two sessionStorage lines have gone. The module deals only with the session.

8.5 The persistence plugin and the store

Create src/store/plugins/persistence.js with the code from section 5.2. And replace src/store/index.js:

// src/store/index.js
// Colmena Bookings store (Vuex 4)
import { createStore, createLogger } from 'vuex'
import { api as colmenaApi } from '@/api'
import { createRoomsModule } from './modules/rooms.js'
import { createBookingsModule } from './modules/bookings.js'
import { createSessionModule } from './modules/session.js'
import { createPersistence } from './plugins/persistence.js'

const PERSISTENCE_RULES = [
  // The session lasts as long as the tab, as before
  { module: 'session', fields: ['name', 'email', 'plan', 'role'], storage: sessionStorage, key: 'colmena-session' },
  // Local copy of the bookings: shown instantly on reload while the API responds
  { module: 'bookings', fields: ['byId', 'ids'], storage: localStorage, key: 'colmena-cache-bookings' }
]

export function createAppStore({ api = colmenaApi, persist = true } = {}) {
  const plugins = []
  if (persist) plugins.push(createPersistence(PERSISTENCE_RULES))
  if (import.meta.env.DEV) plugins.push(createLogger({ collapsed: true }))

  return createStore({
    strict: import.meta.env.DEV,
    modules: {
      rooms: createRoomsModule(api),
      bookings: createBookingsModule(api),
      session: createSessionModule(api)
    },
    plugins
  })
}

export default createAppStore()
  • The session is saved in sessionStorage under the same key as before (colmena-session): anyone who had a session open keeps it.
  • The bookings are saved in localStorage as a cache: when the dashboard is reloaded, the list appears instantly and loadBookings refreshes it in the background (the view already shows the list while loading is true, thanks to the condition we wrote in 05-04). Do not confuse the two keys: colmena-api-bookings is the simulated "server's database"; colmena-cache-bookings is the client's copy.
  • On signing out, bookings/clear leaves the cache empty: the next user of the browser will not see the previous user's bookings.
  • createAppStore({ api, persist }): in tests, you will be able to create a store with a fake API and without touching storage.
  • createLogger in development only. If you find the console noisy, remove it: DevTools shows the same information.

Nothing changes in main.js or in the router: they still import the default store.

8.6 DashboardBookingsView takes advantage of the new getters

In the script of DashboardBookingsView.vue, replace the reading of list, sortedBookings, newBooking and the cancellation:

// DashboardBookingsView.vue
const bookings = computed(() => store.getters['bookings/myBookings']) // already sorted
const newBooking = computed(() => store.getters['bookings/bookingById'](newBookingId.value))

function isCancelling(id) {
  return store.getters['bookings/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 store.dispatch('bookings/cancelBooking', booking.id)
  } catch (e) {
    cancellationError.value = `Could not cancel the booking on ${booking.date}: ${e.message}. It has been restored.`
  }
}

Delete sortedBookings and the cancellingId ref. In the template, the v-for iterates over bookings and the button uses the getter:

<li v-for="booking in bookings" :key="booking.id" :class="{ 'booking-list__new': booking.id === newBookingId }">
  <!-- badge and details, unchanged -->
  <BaseButton
    v-if="booking.status !== 'cancelled'"
    variant="danger"
    :disabled="isCancelling(booking.id)"
    @click="cancel(booking)"
  >
    Cancel
  </BaseButton>
</li>

(Also change the two conditions in the template that used sortedBookings.length to bookings.length.) With optimistic cancellation, the button disappears as soon as the dialog is confirmed, because the booking becomes 'cancelled' instantly; if the API fails, it reappears along with the notice.

8.7 Try it

  1. Normalisation. In the Vuex inspector, expand bookings: you will see byId (an object indexed by id) and ids. Among the getters, bookings/myBookings shows the list already sorted.
  2. Selectors. As Laura, "My bookings" shows only hers (two demo bookings plus any you have created). Sign out and sign in as Marta (a manager): you see all of them, and the month's amount changes.
  3. No duplicates. Sign out, open the Network tab (or watch the timeline) and sign in with a redirect to /dashboard/bookings: the bookings/loadBookings action is dispatched twice (from signIn and from the view), but there is only one startLoading → setBookings sequence.
  4. Optimistic. Cancel a booking: the badge changes instantly. Now set ERROR_PROBABILITY = 1 in src/api/simulation.js and cancel another one: the badge changes and, a second later, goes back to its previous status with the "It has been restored" notice. In the timeline you will see setStatus twice. Set ERROR_PROBABILITY back to 0.1.
  5. Persistence. With the session started, reload on /dashboard/bookings: the list appears without the "Loading your bookings…" message (it comes from the cache) and is updated when the response arrives. In Local Storage you will see colmena-cache-bookings; in Session Storage, colmena-session.
  6. Console logging. Open the console: each mutation appears as a collapsed group with the previous and next state.
  7. Signing out. Sign out and examine colmena-cache-bookings: it is empty.

Common Mistakes and Tips

  • Normalising and forgetting to update the ids: adding to byId without ids.push leaves the entity invisible in the lists. Keep both operations together in one mutation (saveBooking).
  • Storing promises, timers or AbortControllers in the state. They are not serialisable; they belong in module (or factory) variables.
  • An optimistic update without a rollback (or without a warning). The user believes something was done when it was not. Always roll back and explain why.
  • Persisting the whole state. Restoring loading: true or an old error leaves the application in absurd states. Persist only the fields you need.
  • Persisting a user's data in localStorage without clearing it on sign-out: the next user of the same browser will see it. And never persist secrets (passwords, long-lived tokens) in storage accessible from JavaScript.
  • Leaving createLogger or strict mode enabled in production. A performance cost and a cluttered console. Make them conditional on import.meta.env.DEV.
  • Importing the real API directly into the modules when they are going to be tested: it forces you to intercept imports. Inject the API.
  • Tip: before applying a pattern, ask yourself what specific problem it solves in your application (the table in section 7). A five-room store does not need normalisation; one with thousands of bookings does.
  • Tip: when you come across plugins such as vuex-persistedstate or module factories in a legacy project, you now know what they do inside. That is what will let you replace them safely.

Exercises

Exercise 1. Add to the bookings module a bookingsByRoom getter that returns an object { [roomId]: [that room's active bookings, sorted] } by composing existing selectors, and use it to show the room's upcoming bookings in RoomDetailView. Which getter should it start from?

Exercise 2. Make createBooking optimistic: add the booking instantly with a temporary id ('tmp-' + crypto.randomUUID()) and 'pending' status, and replace it with the server's when it responds (or remove it if it fails). You will need a new mutation. Then explain why, in Colmena, it is not a good idea.

Exercise 3. Write a createActionTimer() plugin that, with store.subscribeAction, measures how long each action takes and writes a warning to the console if any takes longer than 1 second ("[Colmena] bookings/loadBookings took 1340 ms"). Register it in development only.

Solutions

Solution 1.

// getters in the bookings module
bookingsByRoom: (state, getters) => Object.groupBy(getters.activeBookings, (b) => b.roomId)

It should start from activeBookings, which is already filtered and sorted (because it in turn starts from sortedBookings): Object.groupBy preserves the order within each group. Starting from the state would force you to repeat the filtering and the sorting.

// RoomDetailView.vue
store.dispatch('bookings/loadBookings')
const upcomingBookings = computed(() => store.getters['bookings/bookingsByRoom'][id] ?? [])
<section v-if="upcomingBookings.length">
  <h3>Upcoming bookings</h3>
  <ul>
    <li v-for="b in upcomingBookings" :key="b.id">{{ b.date }} · {{ b.startTime }}–{{ b.endTime }}</li>
  </ul>
</section>

Showing any visitor other members' bookings (even if only the times) is a privacy decision; in a real application, the API would return only the occupancy, without names.

Solution 2.

// mutations
removeBooking(state, id) {
  delete state.byId[id]
  state.ids = state.ids.filter((x) => x !== id)
}

// actions
async createBooking({ commit }, data) {
  const tempId = `tmp-${crypto.randomUUID()}`
  commit('saveBooking', { ...data, id: tempId, status: 'pending' })
  try {
    const created = await api.bookings.createBooking(data)
    commit('removeBooking', tempId)
    commit('saveBooking', created)
    return created
  } catch (error) {
    commit('removeBooking', tempId)
    throw error
  }
}

It is not a good idea in Colmena because creation fails for business reasons fairly often (overlaps that only the server can check) and because the id is assigned by the server: the view needs the final one to navigate to "My bookings" with ?new=. Showing a booking that disappears a few seconds later because of an overlap would be more confusing than the wait, which, besides, the form already covers.

Solution 3.

// src/store/plugins/actionTimer.js
export function createActionTimer({ thresholdMs = 1000 } = {}) {
  return (store) => {
    const startTimes = new Map()
    store.subscribeAction({
      before: (action) => {
        startTimes.set(action, performance.now())
      },
      after: (action) => {
        const duration = performance.now() - startTimes.get(action)
        startTimes.delete(action)
        if (duration > thresholdMs) {
          console.warn(`[Colmena] ${action.type} took ${Math.round(duration)} ms`)
        }
      },
      error: (action) => {
        startTimes.delete(action)
      }
    })
  }
}
// src/store/index.js
if (import.meta.env.DEV) plugins.push(createLogger({ collapsed: true }), createActionTimer())

With the object form, subscribeAction notifies before and after the action's promise resolves. The action object itself serves as the Map key because it is the same one in before and in after. Actions that do not exceed the threshold do not clutter the console.

Conclusion

The patterns in this lesson are what separate a store that works from one that scales. Normalising collections (byId + ids) turns lookups into direct access and avoids duplicate copies. Getters as composable selectors keep each rule in a single place and chain their caches. Complex asynchronous actions fire requests in parallel, share the promise of a load in progress so as not to duplicate it, store the state of each operation per entity and apply optimistic updates with rollback. The repository pattern makes the store depend on an injected API, swappable in tests, and plugins (with subscribe, subscribeAction and replaceState) move cross-cutting responsibilities such as persistence or logging with createLogger out of the modules, always with strict mode and the debugging tools restricted to development. Colmena now has src/api/index.js, modules created with factories, normalised bookings with optimistic cancellation, requests without duplicates and a plugin that persists the session and a bookings cache.

If you review the code in this module, you will also see its cost: to cancel a booking we have written one action and three mutations whose only role is to assign values; every name travels through the code as a string ('bookings/cancelBooking') that the editor cannot check; reading a value requires a computed property with square brackets and prefixes; and half the lines in each module are ceremony. That cost is what led the Vue team to rethink state management from scratch, taking advantage of the Composition API. The result is a simpler library, with no mutations, with modular stores by design and no magic strings, which today is the official recommendation for any Vue 3 project. You will meet it in the next lesson, Pinia: The Recommended State Management for Vue 3, where Colmena will create its first Pinia store, living side by side with the Vuex store you have just built.

© Copyright 2026. All rights reserved