Vue 3·Vue from reactivity to a routed app

Pinia and a capstone app

Share state with Pinia and assemble a routed course browser.

Intermediate 22 min read Lesson 10 of 300 Challenge included
What you will be able to do
  • Create a store with defineStore.
  • Use state, getters and actions.
  • Keep async work in actions.
  • Persist only what must survive a reload.

In plain English

Pinia stores hold shared state, getters and actions. Keep server data and UI state separate, and let components read from the store instead of prop-drilling through five layers. The capstone combines routing, fetching, forms and a store.

stores/courses.jsJavaScript
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useCourses = defineStore('courses', () => {
  const items = ref([])
  const query = ref('')
  const filtered = computed(() =>
    items.value.filter((course) => course.title.toLowerCase().includes(query.value.toLowerCase())),
  )

  async function load() {
    const response = await fetch('/api/courses')
    items.value = await response.json()
  }

  return { items, query, filtered, load }
})
Your turn

Add a loading action state

Medium

Add a loading boolean to the store and set it around the load action.

JAVASCRIPT · starter
const loading = ref(false)
Check your understanding before moving on.
Knowledge checkQuestion 1

When should state live in a Pinia store?

Select an answer to continue
Study tools

Make it yours.

Keep a private note for this lesson, then turn the key ideas into flashcards you can revisit.

Sign in to save notes and flashcards.Both are private to your account and stay with your progress.
Sign in
Finished reading?

Lock in what you just learned.

Mark this lesson complete to save your place and move one step closer to the certificate.

Lesson 10 of 300 · 0% of course