EthicsComputerCourses
Join training +91 90532 10052

State Management with Pinia

MEVN Stack · Lesson 12 of 20 Intermediate 11 min read Updated

By the end of this lesson NoteNest's notes will live in one Pinia store instead of inside a page. The list page, the header and the note page will all read the same data, a pin on one screen will update the others at once, and the store will be ready to forget everything when a user logs out. You will also learn which data belongs in a store, which belongs in the URL and which should stay inside a component.

What you should know first: Routing with Vue Router, where the loading logic moved into NotesView.vue. Pinia itself is taught in State Management with Pinia and Pinia Patterns at Scale; here we focus on a store that talks to the Express API. Versions checked: Pinia 4.1.0 with Vue 3.5 and Vue Router 5.5.1.

Why the notes need a shared home

After the routing lesson, the notes array lives inside NotesView. That works until a second component needs it. We want three things:

  • The header in App.vue shows "3 notes, 1 pinned". The header is not a child of NotesView, so it cannot receive the notes as a prop.
  • The note page should show a note at once if the list already loaded it, instead of a "Loading..." flash.
  • When Priya logs out, every note she loaded must disappear from memory before Rohan logs in on the same laptop.

Passing data through many layers of props, or emitting events up many layers, gets messy fast. A store is a single shared object that any component can use directly. Think of the attendance register in a coaching centre in Rohtak. Teachers in every room read and mark the same register at the front desk; they do not pass loose copies from class to class.

Pinia is the official store library for Vue, and create-vue installed it in Set Up Your MEVN Environment. main.js already has app.use(createPinia()).

Where each kind of state belongs

Not everything goes into a store. Putting the wrong data there is the most common Pinia mistake. NoteNest uses this rule:

Kind of stateExampleWhere it lives
Data from the server, used by several screensThe notes list, load statusPinia store
What the user is looking atThe tag filter, the note idThe URL (router)
Input that only one form usesThe new note title, "saving" flagThe component
Who is logged inThe user objectA second store (next lesson)

The URL keeps the filter, as the routing lesson decided. The store keeps the notes. The form keeps its own text. Each piece of state has exactly one owner.

Step 1: Write the notes store

Create client/src/stores/notes.js. Pinia offers two ways to write a store. This course uses a setup store: a function that looks just like <script setup>, with ref for state, computed for getters and plain functions for actions.

JavaScript
// client/src/stores/notes.js
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import { listNotes, createNote, updateNote, deleteNote } from '@/api/notes.js'

// One shared copy of the user's notes, used by every view.
export const useNotesStore = defineStore('notes', () => {
  // state
  const notes = ref([])
  const status = ref('idle') // 'idle' | 'loading' | 'ready' | 'error'
  const loadError = ref(null)

  // getters
  const sortedNotes = computed(() =>
    notes.value.toSorted(
      (a, b) => Number(b.pinned) - Number(a.pinned) || b.updatedAt.localeCompare(a.updatedAt),
    ),
  )
  const pinnedCount = computed(() => notes.value.filter((n) => n.pinned).length)

  // actions
  let controller = null

  async function fetchNotes(tag = '') {
    controller?.abort() // cancel a slower, older request
    controller = new AbortController()
    const { signal } = controller
    status.value = 'loading'
    try {
      const data = await listNotes(tag, { signal })
      notes.value = data.notes
      status.value = 'ready'
    } catch (err) {
      if (signal.aborted) return // cancelled by a newer call or $reset()
      loadError.value = err
      status.value = 'error'
    }
  }

  async function addNote(title) {
    const data = await createNote({ title })
    notes.value.push(data.note)
    return data.note
  }

  async function togglePin(id) {
    const note = notes.value.find((n) => n.id === id)
    if (!note) return
    const before = note.pinned
    note.pinned = !before
    try {
      const data = await updateNote(id, { pinned: note.pinned })
      Object.assign(note, data.note)
    } catch (err) {
      note.pinned = before
      throw err
    }
  }

  async function removeNote(id) {
    await deleteNote(id)
    notes.value = notes.value.filter((n) => n.id !== id)
  }

  function findNote(id) {
    return notes.value.find((n) => n.id === id) ?? null
  }

  function $reset() {
    controller?.abort()
    notes.value = []
    status.value = 'idle'
    loadError.value = null
  }

  return {
    notes, status, loadError,
    sortedNotes, pinnedCount,
    fetchNotes, addNote, togglePin, removeNote, findNote, $reset,
  }
})

Some choices to notice:

  • The id 'notes' is the store's name in DevTools. Each store needs a unique one.
  • Cancellation moved in. In the last two lessons, onWatcherCleanup aborted the old request. A store has no watcher, so it keeps the current AbortController in a variable and aborts it when a newer fetchNotes starts. The race-condition fix from Fetching Data with the Composition API still holds, now for every component that calls the store.
  • signal.aborted is checked instead of err.name. A request cancelled at an awkward moment can fail in other ways, and the store must ignore all of them, not only AbortError.
  • Actions throw for user actions. togglePin rolls back its optimistic change, then re-throws, so the page that called it can show the message. fetchNotes keeps its error in state instead, because several components read it.
  • $reset is written by hand. Pinia gives a built-in $reset() only to option stores, because it cannot guess the starting values of a setup function. The next lesson calls it at logout.
  • Return everything. Pinia only tracks the state you return. A private ref that is not returned is invisible to DevTools and to tests.

Step 2: Use the store in NotesView

NotesView.vue becomes much shorter. It keeps the URL logic and the form, and hands everything about notes to the store.

HTML
<!-- client/src/views/NotesView.vue (script setup) -->
<script setup>
import { ref, computed, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import NoteCard from '@/components/NoteCard.vue'
import { useNotesStore } from '@/stores/notes.js'

const route = useRoute()
const router = useRouter()
const store = useNotesStore()

// State and getters need storeToRefs to stay reactive; actions do not.
const { sortedNotes, status, loadError } = storeToRefs(store)
const { fetchNotes, addNote, togglePin, removeNote } = store

// The tag filter still lives in the URL: /?tag=college
const tag = computed(() => (typeof route.query.tag === 'string' ? route.query.tag : ''))
const tagInput = ref(tag.value)
watch(tag, (currentTag) => {
  tagInput.value = currentTag
  fetchNotes(currentTag)
}, { immediate: true })

function applyFilter() {
  const value = tagInput.value.trim()
  router.push({ query: value ? { tag: value } : {} })
}

// Form state stays local: no other component needs it.
const newTitle = ref('')
const saving = ref(false)
const actionError = ref('')

async function run(action) {
  actionError.value = ''
  try {
    await action()
  } catch (err) {
    actionError.value = err.message
  }
}

async function submitNote() {
  saving.value = true
  await run(async () => {
    await addNote(newTitle.value)
    newTitle.value = ''
  })
  saving.value = false
}
</script>

In the template, the cards now call the store through the small run helper, which turns any thrown error into the alert text:

HTML
<NoteCard
  v-for="note in sortedNotes"
  :key="note.id"
  :note="note"
  @toggle-pin="run(() => togglePin(note.id))"
  @remove="run(() => removeNote(note.id))"
/>

The rest of the template stays the same, except that the form's submit handler is now submitNote and the empty check reads sortedNotes.length === 0.

Why storeToRefs? A store is a reactive object. Destructuring it with const { status } = store copies the current value into a plain variable, and that variable never changes again. storeToRefs(store) instead gives you a ref for every state field and getter, linked to the store. Actions are plain functions, so you can destructure them directly. The page below shows the trap with a plain reactive object, which behaves the same way as a store here.

HTMLOpen in editor
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Shared state and the destructuring trap</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@3.5.44/dist/vue.global.prod.js"></script>
  <style>
    body { font-family: system-ui, sans-serif; margin: 16px; max-width: 34rem; }
    header { background: #42b883; color: #fff; padding: 8px; border-radius: 6px; }
    li { margin: 6px 0; }
    .bad { color: #b00020; }
  </style>
</head>
<body>
  <div id="app"></div>

  <script>
    const { createApp, reactive, computed, toRefs } = Vue;

    // A tiny "store": one reactive object that every component imports
    const store = reactive({
      notes: [
        { id: "n1", title: "DBMS viva questions", pinned: true },
        { id: "n2", title: "Sunday groceries", pinned: false },
        { id: "n3", title: "Train to Jaipur", pinned: false }
      ],
      get pinnedCount() { return this.notes.filter((n) => n.pinned).length; },
      togglePin(id) {
        const note = this.notes.find((n) => n.id === id);
        note.pinned = !note.pinned;
      }
    });

    const TopBar = {
      setup() {
        const copied = store.pinnedCount;          // a plain number: the trap
        const { notes } = toRefs(store);           // a ref linked to the store
        return { store, copied, notes };
      },
      template: `<header>
        {{ notes.length }} notes, {{ store.pinnedCount }} pinned
        <span class="bad">(copied value: {{ copied }})</span>
      </header>`
    };

    const NoteList = {
      setup() { return { store }; },
      template: `<ul><li v-for="n in store.notes" :key="n.id">
        {{ n.pinned ? '[Pinned] ' : '' }}{{ n.title }}
        <button type="button" @click="store.togglePin(n.id)">{{ n.pinned ? 'Unpin' : 'Pin' }}</button>
      </li></ul>`
    };

    createApp({
      components: { TopBar, NoteList },
      template: `<TopBar /><NoteList />`
    }).mount("#app");
  </script>
</body>
</html>

Pin "Train to Jaipur" in the list and the header's live count changes, because both components read the same object. The red "copied value" stays at 1 forever: it was copied once, when the header was created. That is exactly what happens with const { pinnedCount } = useNotesStore().

Step 3: Read the store from other components

The header in App.vue now shows the counts. It uses the store object directly in the template, which is also reactive and needs no storeToRefs:

HTML
<!-- client/src/App.vue (changed parts) -->
<script setup>
import { RouterLink, RouterView } from 'vue-router'
import { useNotesStore } from '@/stores/notes.js'

const notesStore = useNotesStore()
</script>

<template>
  <header class="top-bar">
    <RouterLink to="/" class="brand">NoteNest</RouterLink>
    <span v-if="notesStore.status === 'ready'">
      {{ notesStore.notes.length }} notes, {{ notesStore.pinnedCount }} pinned
    </span>
  </header>
  <main class="page">
    <RouterView />
  </main>
</template>

The note page uses the cache. In NoteDetailView.vue, add const store = useNotesStore() and change the start of the watcher:

JavaScript
// client/src/views/NoteDetailView.vue (inside the watcher, before the try)
// Show the copy the list already loaded at once, then refresh it.
note.value = store.findNote(id)
status.value = note.value ? 'ready' : 'loading'

The page still fetches the note from the API, because the cached copy may be old, but the user sees the title immediately. Opening a note straight from a bookmark still works: the store is empty, so the page shows "Loading note..." first, as before.

Step 4: Watch the pieces stay in step

We logged in as Priya and drove the page in headless Chrome. We read the header, pinned "Train to Jaipur", read the header and card titles again, unpinned it, and finally opened the first note:

Output
NoteNest
3 notes, 1 pinned

NoteNest
3 notes, 2 pinned | Train to Jaipur / DBMS viva questions / Sunday groceries

NoteNest
3 notes, 1 pinned

One action in the store changed the card, the sort order and the header together, and nothing had to emit an event across the app. The note page then showed "DBMS viva questions" with no loading line, because it came from the store.

Vue DevTools (the address Vite prints) can also show the notes store and its current state, which is a quick way to see why a value changed.

Common mistakes

  • Destructuring a store without storeToRefs. The values freeze. Use storeToRefs for state and getters, plain destructuring only for actions.
  • Putting everything in the store. Form text and "is this menu open" belong to one component. The URL owns filters and ids.
  • Forgetting to return state from a setup store. Unreturned refs do not show in DevTools and break tests that read them.
  • Calling useNotesStore() outside a component before app.use(createPinia()). You get an error that there is no active Pinia. Call stores inside setup, actions, guards or functions that run after the app starts.
  • Not clearing user data at logout. The next person on the same browser sees the old notes until a reload. Add a $reset now.

Interview questions

1. When should data live in a Pinia store instead of a component?

When several components that are not parent and child need the same data, or when the data must survive navigation between pages. Data that only one component uses, such as a form's input, should stay local, and state a user may bookmark belongs in the URL.

2. Why do you need storeToRefs when destructuring a store?

A store is a reactive object, and destructuring copies the current values into plain variables that are no longer reactive. storeToRefs creates refs linked to each state property and getter, so the destructured names keep updating. Actions are not reactive data and can be destructured directly.

3. What is the difference between a setup store and an option store?

An option store passes an object with state, getters and actions, similar to the Options API. A setup store passes a function that uses ref, computed and functions, like <script setup>, and must return everything. Setup stores can use composables and watchers freely but need a hand-written $reset.

4. How do you avoid a race condition when a store action fetches data?

Keep the current AbortController in the store, abort it when a new request starts, and ignore results or errors from a request whose signal was aborted. Then a slow old response can never overwrite newer data.

Key points

  • useNotesStore is a setup store: refs for state, computed for getters, functions for actions, all returned.
  • Server data shared by several screens goes in the store; filters and ids stay in the URL; form input stays in the component.
  • Use storeToRefs for state and getters; destructure actions directly.
  • fetchNotes keeps one AbortController and ignores aborted requests, so the race-condition fix works for every caller.
  • Actions throw for user-triggered failures after rolling back; the page shows the message.
  • A hand-written $reset clears the notes, ready for logout in the next lesson.

Exercise

Add an allTags getter to the notes store that returns every tag used by the loaded notes, without repeats, sorted A to Z. Then show the tags as links above the list in NotesView, each one going to /?tag=<that tag>, with the current tag in bold. Which existing piece of code reloads the notes when a tag link is clicked?

Show solution

In stores/notes.js, add the getter and return it:

JavaScript
const allTags = computed(() => [...new Set(notes.value.flatMap((n) => n.tags))].sort())

In NotesView.vue, take it with storeToRefs together with the others, then add to the template:

HTML
<nav aria-label="Tags">
  <RouterLink
    v-for="t in allTags"
    :key="t"
    :to="{ name: 'notes', query: { tag: t } }"
    :style="{ fontWeight: t === tag ? 'bold' : 'normal' }"
  >
    {{ t }}
  </RouterLink>
</nav>

Nothing new reloads the notes. A link changes the URL query, the tag computed changes, and the existing watch(tag, ...) calls fetchNotes. One catch: while a tag is selected, allTags only knows the tags of the filtered notes, so the bar shrinks. To keep the full list, the server needs its own endpoint, such as the GET /api/tags exercise from Build a REST API with Express 5.

Quick Quiz

1. Where should NoteNest keep the text a user is typing into the "New note" box?

2. What happens with const { pinnedCount } = useNotesStore() in a component?

3. Why does the NoteNest setup store define its own $reset function?

4. Why does fetchNotes check signal.aborted in its catch block?

Learn MEVN Stack with a mentor

Free lessons get you started. Our Full Stack Web Development training adds real projects and code reviews from working developers.

  • Project-based learning
  • Mentor code reviews
  • Free counselling call