Vue.js course ยท Module 11: Pinia

Plugins and Persistence

2 min read ยท
In this lesson6

The NOVA LAB backup system ensures that critical data survives even a station restart. In Pinia, this role is fulfilled by plugins - extensions that add new capabilities to stores. The most important one is persistence - saving state to localStorage.

$subscribe - Listening for Changes

$subscribe allows reacting to every state change:

const store = useResourceStore()

store.$subscribe((mutation, state) => {
  console.log('Store changed:', mutation.storeId)
  console.log('Type:', mutation.type) // 'direct' | '$patch'
  console.log('New state:', state)

  // Automatic save to localStorage
  localStorage.setItem('resources', JSON.stringify(state))
})

Subscribe options:

store.$subscribe(
  (mutation, state) => { /* ... */ },
  { detached: true } // Survives component unmount
)

$onAction - Observing Actions

const store = useResourceStore()

store.$onAction(({ name, args, after, onError }) => {
  console.log(`Action started: ${name}`, args)

  after((result) => {
    console.log(`Action ${name} completed`, result)
  })

  onError((error) => {
    console.error(`Action ${name} failed`, error)
  })
})

Persistence Plugin

The most popular plugin - pinia-plugin-persistedstate:

npm install pinia-plugin-persistedstate

Configuration:

// main.js
import { createPinia } from 'pinia'
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'

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

Usage in a store:

export const useSettingsStore = defineStore('settings', () => {
  const theme = ref('dark')
  const language = ref('en')

  return { theme, language }
}, {
  persist: true // Entire state to localStorage
})

Advanced Persist Configuration

export const useAuthStore = defineStore('auth', () => {
  const token = ref(null)
  const user = ref(null)
  const tempData = ref(null) // We don't want to save this

  return { token, user, tempData }
}, {
  persist: {
    // Only selected fields
    pick: ['token'],

    // Custom storage
    storage: sessionStorage,

    // Custom key
    key: 'nova-lab-auth'
  }
})

Creating a Custom Plugin

A Pinia plugin is a function that receives a context with the store:

// plugins/logger.js
export function loggerPlugin({ store }) {
  store.$subscribe((mutation, state) => {
    console.log(`[${mutation.storeId}] ${mutation.type}`)
  })

  store.$onAction(({ name, store: s, args }) => {
    console.log(`[${s.$id}] Action: ${name}`, args)
  })
}

// main.js
const pinia = createPinia()
pinia.use(loggerPlugin)

Plugin Adding Properties

function timestampPlugin({ store }) {
  // Add lastUpdated to every store
  store.lastUpdated = ref(null)

  store.$subscribe(() => {
    store.lastUpdated = new Date()
  })
}
Code for this lesson: App.vue
<script setup>
import { ref, computed, watch } from 'vue'

// Store simulation with $subscribe and plugins
const settings = ref({
  theme: 'dark',
  language: 'pl',
  fontSize: 14
})

const changeLog = ref([])
const actionLog = ref([])

// $subscribe simulation
watch(settings, (newVal) => {
  changeLog.value.unshift({
    time: new Date().toLocaleTimeString(),
    change: JSON.stringify(newVal)
  })
  if (changeLog.value.length > 6) changeLog.value.pop()

  // Persist simulation - save to localStorage
  try {
    localStorage.setItem('nova-settings', JSON.stringify(newVal))
  } catch (e) {}
}, { deep: true })

// $onAction simulation (logger plugin)
function logAction(name, args = []) {
  actionLog.value.unshift({
    time: new Date().toLocaleTimeString(),
    action: name,
    args: args.length ? JSON.stringify(args) : '-'
  })
  if (actionLog.value.length > 6) actionLog.value.pop()
}

// Actions
function toggleTheme() {
  settings.value.theme = settings.value.theme === 'dark' ? 'light' : 'dark'
  logAction('toggleTheme')
}

function setLanguage(lang) {
  settings.value.language = lang
  logAction('setLanguage', [lang])
}

function changeFontSize(delta) {
  settings.value.fontSize = Math.max(10, Math.min(24, settings.value.fontSize + delta))
  logAction('changeFontSize', [delta])
}

function resetSettings() {
  settings.value = { theme: 'dark', language: 'pl', fontSize: 14 }
  logAction('resetSettings')
}

const persistedData = computed(() => {
  try {
    return localStorage.getItem('nova-settings') || 'No data'
  } catch (e) {
    return 'Storage not available'
  }
})
</script>

<template>
  <div class="nova-lab" :class="settings.theme" :style="{ fontSize: settings.fontSize + 'px' }">
    <h1>NOVA LAB - Plugins & Persistence</h1>

    <div class="grid">
      <div class="panel">
        <h2>Settings Store</h2>
        <div class="setting">
          <span>Theme:</span>
          <button @click="toggleTheme" class="btn">{{ settings.theme }}</button>
        </div>
        <div class="setting">
          <span>Language:</span>
          <button @click="setLanguage('pl')" class="btn" :class="{ active: settings.language === 'pl' }">PL</button>
          <button @click="setLanguage('en')" class="btn" :class="{ active: settings.language === 'en' }">EN</button>
        </div>
        <div class="setting">
          <span>Font:</span>
          <button @click="changeFontSize(-2)" class="btn">A-</button>
          <span>{{ settings.fontSize }}px</span>
          <button @click="changeFontSize(2)" class="btn">A+</button>
        </div>
        <button @click="resetSettings" class="btn btn-reset">Reset All</button>
      </div>

      <div class="panel">
        <h2>$subscribe Log</h2>
        <div v-for="(entry, i) in changeLog" :key="i" class="log-entry">
          <span class="time">{{ entry.time }}</span>
          <span class="change">{{ entry.change }}</span>
        </div>
        <p v-if="!changeLog.length" class="empty">No changes yet</p>
      </div>

      <div class="panel">
        <h2>$onAction Log (plugin)</h2>
        <div v-for="(entry, i) in actionLog" :key="i" class="log-entry">
          <span class="time">{{ entry.time }}</span>
          <span class="action-name">{{ entry.action }}</span>
          <span class="args">{{ entry.args }}</span>
        </div>
        <p v-if="!actionLog.length" class="empty">No actions yet</p>
      </div>

      <div class="panel">
        <h2>Persisted (localStorage)</h2>
        <pre class="persisted">{{ persistedData }}</pre>
      </div>
    </div>
  </div>
</template>

<style scoped>
.nova-lab {
  min-height: 100vh;
  padding: 20px;
  font-family: monospace;
  transition: all 0.3s;
}
.nova-lab.dark { background: #0a0e27; color: #00ff88; }
.nova-lab.light { background: #f0f4f8; color: #1a1e3f; }
h1 { margin-bottom: 20px; text-align: center; }
h2 { color: #00b4d8; margin-bottom: 10px; font-size: 1em; }
.grid { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; max-width: 700px; margin: 0 auto; }
.panel {
  background: rgba(0, 180, 216, 0.1);
  border: 2px solid #00b4d8;
  padding: 12px;
}
.setting { display: flex; align-items: center; gap: 8px; margin: 8px 0; flex-wrap: wrap; }
.btn {
  background: #00b4d8;
  color: #0a0e27;
  border: none;
  padding: 4px 12px;
  cursor: pointer;
  font-family: monospace;
}
.btn:hover { background: #00ff88; }
.btn.active { background: #00ff88; }
.btn-reset { background: #ff9900; margin-top: 10px; }
.log-entry {
  padding: 4px 0;
  border-bottom: 1px solid rgba(0, 180, 216, 0.2);
  font-size: 0.8em;
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}
.time { color: #00b4d8; }
.change { color: #00ff88; word-break: break-all; }
.action-name { color: #ff9900; }
.args { color: #666; }
.empty { color: #666; font-style: italic; font-size: 0.85em; }
.persisted {
  background: #0a0e27;
  color: #00ff88;
  padding: 8px;
  font-size: 0.75em;
  word-break: break-all;
  white-space: pre-wrap;
}
</style>

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. What does the $subscribe method do?

  2. 2. What does the pinia-plugin-persistedstate do?

These are 2 of 6 questions for this lesson. Solve the rest in the game.

Hands-on tasks in the game

  • Code editor

    Create a log store with addLog, clearLogs and a plugin that logs changes to the console.

  • Vertical ordering

    Arrange the steps for configuring the persistence plugin

  • Vertical ordering

    Arrange the stages of the $subscribe execution flow

  • Code editor

    Create a resource store with alerts and a statusLevel getter - consume creates alerts.

  • Click in order

    Arrange the elements of a Pinia plugin pattern

  • Vertical ordering

    Arrange the elements of advanced persistence configuration

  • Horizontal ordering

    Arrange the elements to access state in a store

  • Vertical ordering

    Arrange the stages of data flow in Pinia

  • Horizontal ordering

    Arrange the elements to use $patch with a function

  • Click in order

    Arrange the elements of the full store lifecycle

  • Vertical ordering

    Arrange the criteria for choosing Pinia vs provide/inject

  • Vertical ordering

    Arrange the steps for registering a Pinia plugin

  1. Question$subscribe in Pinia
  2. QuestionPersistence Plugin
  3. Coding taskPractice: $subscribe and Persistence
  4. Put in orderPersistence Configuration
  5. Question$onAction in Pinia
  6. Put in order$subscribe Flow
  7. QuestionCustom Plugin
  8. Coding taskPractice: Complete Logging System
  9. Click in orderPlugin Pattern
  10. Put in orderAdvanced Persist Configuration
  11. Put in orderAccessing State in a Store
  12. QuestionDevTools in Pinia
  13. Put in orderData Flow in Pinia
  14. QuestionVuex vs Pinia - Mutations
  15. Put in order$patch with a Function
  16. Click in orderFull Store Lifecycle
  17. Put in orderWhen to Use Pinia vs provide/inject?
  18. Put in orderPinia Plugin Registration

Useful articles