Web frameworks · Intermediate · 26 min
Share state between Vue components with Pinia and Vue Router
By Padding · Updated 18 Nov 2026
Debian (node:26 image) · Node.js 26.13 · Vue 3.5.45 · Pinia 4.1.0 · Vue Router 5.5.1 · Vite 8.3 · Vitest 5.1
You will build a three-page Vue 3.5 shop with Vue Router 5.5 and a Pinia 4.1 basket store that keeps its contents across pages and reloads, places orders through a local API and is covered by Vitest tests.
On this page
A Vue component owns its own refs. That works until two components that are not parent and child need the same data, and the shopper expects it to still be there after moving to another page. A shop basket is the classic case: the product page adds to it, the header counts it, the basket page lists and sends it. Passing it through props from App.vue turns every page into a courier for data it does not use.
Pinia gives that data one home. A store is a function you call from any component; every caller gets the same reactive object, and it lives for as long as the app does, so it survives route changes. A setup store is written with the same ref, computed and functions you already use in components, which makes it the shortest step from the Composition API.
In this tutorial you build a small stationery stall. You scaffold a project, add three routes (one with a dynamic product number), create a setup-style basket store, read it from two pages, add getters, place orders through a local Node.js API with an async action, keep the basket in localStorage and test the store with Vitest. You start a fresh project with the same create-vue tool as the first Vue tutorial, so you do not need your reading-list code.
Commands are for a Linux or macOS shell, or WSL on Windows. You need three terminals: one for the API, one for the Vite dev server and one for everything else.
Step 1 · Create the project and pin the packages
Scaffold a TypeScript project with no example code. --bare skips the starter components, which you would only delete:
cd ~
npm create vue@3.24.0 -- --ts --bare vue-stall
cd vue-stall
npm installAdd Vue Router, Pinia and Vitest at exact versions so what you see matches this page:
npm install --save-exact vue@3.5.45 vue-router@5.5.1 pinia@4.1.0 @vue/devtools-api@8.2.1
npm install --save-dev --save-exact vitest@5.1.1 jsdom@31.0.1
npm pkg set scripts.test="vitest run"Two notes on that list. Pinia 4 no longer bundles @vue/devtools-api; it is a peer dependency you install yourself, which is why it is named here. Pinia 4 is also ESM only, which a Vite project already is. Vue Router 5 has no breaking changes for an app that defines its routes in code, as this one does.
Check it worked
npm ls vue vue-router pinia vitest --depth=0The tree lists vue@3.5.45, vue-router@5.5.1, pinia@4.1.0 and vitest@5.1.1. src/ holds little more than App.vue and main.ts.
Step 2 · Add three routes with a dynamic product number
The stall sells four items. Keep them in a plain module with a currency formatter. Prices are whole naira, stored as integers so sums never pick up floating-point fractions:
mkdir -p src/views src/stores
cat > src/products.ts <<'TS'
export type Product = { id: number; name: string; price: number; blurb: string }
export const products: Product[] = [
{ id: 1, name: 'A5 notebook', price: 1500, blurb: '80 ruled pages, stitched so it lies flat.' },
{ id: 2, name: 'Ballpoint pens, pack of 5', price: 800, blurb: 'Blue ink, medium tip.' },
{ id: 3, name: 'Desk lamp', price: 12000, blurb: 'LED, USB powered, three brightness levels.' },
{ id: 4, name: 'Power bank, 10,000 mAh', price: 4500, blurb: 'Two USB-A ports and one USB-C port.' },
]
export function findProduct(id: number): Product | undefined {
return products.find((product) => product.id === id)
}
export const naira = new Intl.NumberFormat('en-NG', {
style: 'currency',
currency: 'NGN',
minimumFractionDigits: 0,
maximumFractionDigits: 0,
})
TSNow the router. The product route has a dynamic segment, :id, restricted by (\\d+) to digits, so /products/abc does not match at all. props: true hands the param to the component as a prop instead of making it read useRoute(). The basket page is loaded lazily, as a separate file the browser fetches the first time someone opens it:
cat > src/router.ts <<'TS'
import { createRouter, createWebHistory } from 'vue-router'
import HomeView from './views/HomeView.vue'
import ProductView from './views/ProductView.vue'
export const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [
{ path: '/', name: 'home', component: HomeView },
{ path: '/products/:id(\\d+)', name: 'product', component: ProductView, props: true },
{ path: '/basket', name: 'basket', component: () => import('./views/BasketView.vue') },
],
})
TSWrite the three views. ProductView turns the id prop into a product with computed. That matters: going from /products/2 to /products/3 reuses the same component instance instead of creating a new one, so anything worked out once in <script setup> would keep showing the old product. A computed re-runs when the prop changes:
cat > src/views/HomeView.vue <<'VUE'
<script setup lang="ts">
import { naira, products } from '../products'
</script>
<template>
<h1>Stationery stall</h1>
<ul class="products">
<li v-for="product in products" :key="product.id">
<RouterLink :to="{ name: 'product', params: { id: String(product.id) } }">
{{ product.name }}
</RouterLink>
<span>{{ naira.format(product.price) }}</span>
</li>
</ul>
</template>
VUE
cat > src/views/ProductView.vue <<'VUE'
<script setup lang="ts">
import { computed } from 'vue'
import { findProduct, naira, products } from '../products'
const props = defineProps<{ id: string }>()
const product = computed(() => findProduct(Number(props.id)))
const nextId = computed(() => (Number(props.id) % products.length) + 1)
</script>
<template>
<article v-if="product">
<h1>{{ product.name }}</h1>
<p>{{ product.blurb }}</p>
<p class="price">{{ naira.format(product.price) }}</p>
</article>
<h1 v-else>No product number {{ id }}</h1>
<nav class="row">
<RouterLink to="/">All products</RouterLink>
<RouterLink :to="{ name: 'product', params: { id: String(nextId) } }">Next product</RouterLink>
</nav>
</template>
VUE
cat > src/views/BasketView.vue <<'VUE'
<template>
<h1>Your basket</h1>
<p>Your basket is empty.</p>
</template>
VUEGive the app a header with links, a <RouterView> where the current page renders, a small stylesheet, and register the router in main.ts:
cat > src/App.vue <<'VUE'
<template>
<header class="row">
<RouterLink to="/">Products</RouterLink>
<RouterLink to="/basket">Basket</RouterLink>
</header>
<main>
<RouterView />
</main>
</template>
VUE
cat > src/style.css <<'CSS'
body { font-family: system-ui, sans-serif; margin: 2rem auto; max-width: 36rem; padding: 0 1rem; line-height: 1.5; }
.row { display: flex; flex-wrap: wrap; gap: 1rem; align-items: center; }
header { border-bottom: 1px solid #ccc; padding-bottom: 0.5rem; }
.products li { display: flex; flex-wrap: wrap; gap: 0.75rem; }
.in-basket, .muted { color: #555; }
[role="alert"] { color: #a40000; }
CSS
cat > src/main.ts <<'TS'
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router'
import './style.css'
createApp(App).use(router).mount('#app')
TSStart the dev server in your second terminal and leave it running:
npm run devCheck it worked
Open http://localhost:5173/. You see "Stationery stall" and four products with prices such as ₦1,500. Click "Ballpoint pens, pack of 5": the address bar shows /products/2. Click "Next product": the heading changes to "Desk lamp" and the address to /products/3, without a full page load. Type /products/99 into the address bar and the page says "No product number 99".
Step 3 · Create a setup store and read it from two pages
A setup store is defineStore with an id and a function. Inside, a ref is state and a plain function is an action. Whatever the function returns is the store. Pinia creates the store the first time a component calls useBasketStore() and hands every later caller the same instance.
Start with state and actions only. The basket holds lines of product id and quantity, not copies of the product, so a price change in products.ts cannot leave a stale price in the basket:
cat > src/stores/basket.ts <<'TS'
import { defineStore } from 'pinia'
import { ref } from 'vue'
export type Line = { id: number; qty: number }
export const useBasketStore = defineStore('basket', () => {
const lines = ref<Line[]>([])
function add(id: number) {
const line = lines.value.find((l) => l.id === id)
if (line) line.qty++
else lines.value.push({ id, qty: 1 })
}
function remove(id: number) {
lines.value = lines.value.filter((l) => l.id !== id)
}
function quantityOf(id: number) {
return lines.value.find((l) => l.id === id)?.qty ?? 0
}
return { lines, add, remove, quantityOf }
})
TSInstall Pinia in the app. createPinia() makes the object that holds every store:
cat > src/main.ts <<'TS'
import { createPinia } from 'pinia'
import { createApp } from 'vue'
import App from './App.vue'
import { router } from './router'
import './style.css'
createApp(App).use(createPinia()).use(router).mount('#app')
TSNow read the store from two pages. The product page gets an "Add to basket" button and shows how many are already in the basket. The home page marks products that are in the basket. Neither page passes anything to the other:
cat > src/views/ProductView.vue <<'VUE'
<script setup lang="ts">
import { computed } from 'vue'
import { findProduct, naira, products } from '../products'
import { useBasketStore } from '../stores/basket'
const props = defineProps<{ id: string }>()
const basket = useBasketStore()
const product = computed(() => findProduct(Number(props.id)))
const nextId = computed(() => (Number(props.id) % products.length) + 1)
</script>
<template>
<article v-if="product">
<h1>{{ product.name }}</h1>
<p>{{ product.blurb }}</p>
<p class="price">{{ naira.format(product.price) }}</p>
<div class="row">
<button type="button" @click="basket.add(product.id)">Add to basket</button>
<span class="muted">In your basket: {{ basket.quantityOf(product.id) }}</span>
</div>
</article>
<h1 v-else>No product number {{ id }}</h1>
<nav class="row">
<RouterLink to="/">All products</RouterLink>
<RouterLink :to="{ name: 'product', params: { id: String(nextId) } }">Next product</RouterLink>
</nav>
</template>
VUE
cat > src/views/HomeView.vue <<'VUE'
<script setup lang="ts">
import { naira, products } from '../products'
import { useBasketStore } from '../stores/basket'
const basket = useBasketStore()
</script>
<template>
<h1>Stationery stall</h1>
<ul class="products">
<li v-for="product in products" :key="product.id">
<RouterLink :to="{ name: 'product', params: { id: String(product.id) } }">
{{ product.name }}
</RouterLink>
<span>{{ naira.format(product.price) }}</span>
<span v-if="basket.quantityOf(product.id)" class="in-basket">
{{ basket.quantityOf(product.id) }} in basket
</span>
</li>
</ul>
</template>
VUECheck it worked
Open http://localhost:5173/products/1 and click "Add to basket" twice: the line under it reads "In your basket: 2". Click "All products": "A5 notebook" now shows "2 in basket". Click it again and the product page still says 2. The state moved between pages because both read the same store. Reload the page and the basket is empty again; the store lives in memory, which you fix later in this tutorial.
Step 4 · Add getters and a basket page
A getter in a setup store is a computed. Add three: detailed joins each line with its product, count sums the quantities, and total sums the subtotals. They are cached, so ten components showing the count do not each recount the basket:
cat > src/stores/basket.ts <<'TS'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { findProduct } from '../products'
export type Line = { id: number; qty: number }
export const useBasketStore = defineStore('basket', () => {
const lines = ref<Line[]>([])
const detailed = computed(() =>
lines.value.flatMap((line) => {
const product = findProduct(line.id)
return product ? [{ ...line, name: product.name, subtotal: product.price * line.qty }] : []
}),
)
const count = computed(() => lines.value.reduce((sum, line) => sum + line.qty, 0))
const total = computed(() => detailed.value.reduce((sum, line) => sum + line.subtotal, 0))
function add(id: number) {
const line = lines.value.find((l) => l.id === id)
if (line) line.qty++
else lines.value.push({ id, qty: 1 })
}
function remove(id: number) {
lines.value = lines.value.filter((l) => l.id !== id)
}
function quantityOf(id: number) {
return lines.value.find((l) => l.id === id)?.qty ?? 0
}
return { lines, detailed, count, total, add, remove, quantityOf }
})
TSShow the count in the header. App.vue sits outside every page, so this is a third reader of the same store:
cat > src/App.vue <<'VUE'
<script setup lang="ts">
import { useBasketStore } from './stores/basket'
const basket = useBasketStore()
</script>
<template>
<header class="row">
<RouterLink to="/">Products</RouterLink>
<RouterLink to="/basket">Basket ({{ basket.count }})</RouterLink>
</header>
<main>
<RouterView />
</main>
</template>
VUENow the basket page. It pulls state and getters out of the store with storeToRefs. Plain destructuring, const { total } = basket, would copy the number once and never update; storeToRefs gives you refs that stay connected. Actions are plain functions, so call them on the store itself:
cat > src/views/BasketView.vue <<'VUE'
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { naira } from '../products'
import { useBasketStore } from '../stores/basket'
const basket = useBasketStore()
const { detailed, total } = storeToRefs(basket)
</script>
<template>
<h1>Your basket</h1>
<p v-if="detailed.length === 0">Your basket is empty.</p>
<template v-else>
<ul>
<li v-for="line in detailed" :key="line.id" class="row">
<span>{{ line.name }} × {{ line.qty }}</span>
<span>{{ naira.format(line.subtotal) }}</span>
<button type="button" :aria-label="`Remove ${line.name}`" @click="basket.remove(line.id)">
Remove
</button>
</li>
</ul>
<p><strong>Total: {{ naira.format(total) }}</strong></p>
</template>
</template>
VUECheck it worked
Add two notebooks and one desk lamp. The header reads "Basket (3)" on every page. Open the basket: it lists "A5 notebook × 2" at ₦3,000 and "Desk lamp × 1" at ₦12,000, with "Total: ₦15,000". Click "Remove" next to the lamp: the total drops to ₦3,000 and the header to "Basket (2)" at the same moment.
If you use Vue DevTools, its Pinia view shows the basket store, with lines and the three getters, and updates as you click.
Step 5 · Place orders through a local API with an async action
The order goes to a server, which works out the total from its own price list rather than trusting the browser. Create api/server.mjs, a Node.js server with no dependencies. It accepts POST /api/orders, refuses a basket that is empty or names unknown products with 400, waits half a second so you can see the sending state, and replies with an order number and total:
mkdir -p api
cat > api/server.mjs <<'JS'
import { createServer } from 'node:http'
const PRICES = { 1: 1500, 2: 800, 3: 12000, 4: 4500 }
let nextOrderId = 1
function send(res, status, body) {
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8' })
res.end(JSON.stringify(body))
}
createServer(async (req, res) => {
console.log(req.method, req.url)
if (req.method !== 'POST' || req.url !== '/api/orders') return send(res, 404, { error: 'Not found' })
let raw = ''
for await (const chunk of req) raw += chunk
let lines
try {
lines = JSON.parse(raw).lines
} catch {
lines = null
}
const valid =
Array.isArray(lines) &&
lines.length > 0 &&
lines.every((l) => PRICES[l?.id] && Number.isInteger(l.qty) && l.qty > 0)
if (!valid) return send(res, 400, { error: 'Invalid basket' })
await new Promise((resolve) => setTimeout(resolve, 500))
const total = lines.reduce((sum, l) => sum + PRICES[l.id] * l.qty, 0)
send(res, 201, { orderId: nextOrderId++, total })
}).listen(3001, '127.0.0.1', () => console.log('API on http://127.0.0.1:3001'))
JSPoint Vite at it. Replace vite.config.ts with a proxy, so the browser calls /api/... on the page's own origin and Vite forwards the request to port 3001, in both the dev server and the preview server. The file below imports only vite and @vitejs/plugin-vue, which every create-vue project has, so it works whatever else your scaffold put in the old file. If your old file had extra plugins or an @ alias, this app does not use them; keep them if you like. The lines that matter are const proxy = ..., server: { proxy } and preview: { proxy }:
cat > vite.config.ts <<'TS'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const proxy = { '/api': 'http://127.0.0.1:3001' }
export default defineConfig({
plugins: [vue()],
server: { proxy },
preview: { proxy },
})
TSAdd the action. An action in a setup store can be async like any function. checkout tracks a status the page can show, sends the lines, empties the basket only when the server accepts the order, and keeps the basket with an error message when it does not. The guard at the top stops a double click from sending two orders. Adding an item clears the last confirmation, so it never sits above a new basket:
cat > src/stores/basket.ts <<'TS'
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { findProduct } from '../products'
export type Line = { id: number; qty: number }
export type Order = { orderId: number; total: number }
export const useBasketStore = defineStore('basket', () => {
const lines = ref<Line[]>([])
const status = ref<'idle' | 'sending' | 'error'>('idle')
const error = ref('')
const lastOrder = ref<Order | null>(null)
const detailed = computed(() =>
lines.value.flatMap((line) => {
const product = findProduct(line.id)
return product ? [{ ...line, name: product.name, subtotal: product.price * line.qty }] : []
}),
)
const count = computed(() => lines.value.reduce((sum, line) => sum + line.qty, 0))
const total = computed(() => detailed.value.reduce((sum, line) => sum + line.subtotal, 0))
function add(id: number) {
const line = lines.value.find((l) => l.id === id)
if (line) line.qty++
else lines.value.push({ id, qty: 1 })
lastOrder.value = null
}
function remove(id: number) {
lines.value = lines.value.filter((l) => l.id !== id)
}
function quantityOf(id: number) {
return lines.value.find((l) => l.id === id)?.qty ?? 0
}
async function checkout() {
if (lines.value.length === 0 || status.value === 'sending') return
status.value = 'sending'
error.value = ''
try {
const res = await fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ lines: lines.value }),
})
const body = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
lastOrder.value = body as Order
lines.value = []
status.value = 'idle'
} catch (err) {
error.value = err instanceof Error ? err.message : String(err)
status.value = 'error'
}
}
return { lines, status, error, lastOrder, detailed, count, total, add, remove, quantityOf, checkout }
})
TSGive the basket page a button and the two messages. role="status" and role="alert" make screen readers announce them when they appear:
cat > src/views/BasketView.vue <<'VUE'
<script setup lang="ts">
import { storeToRefs } from 'pinia'
import { naira } from '../products'
import { useBasketStore } from '../stores/basket'
const basket = useBasketStore()
const { detailed, total, status, error, lastOrder } = storeToRefs(basket)
</script>
<template>
<h1>Your basket</h1>
<p v-if="lastOrder" role="status">
Order {{ lastOrder.orderId }} placed. Total charged: {{ naira.format(lastOrder.total) }}.
</p>
<p v-if="detailed.length === 0">Your basket is empty.</p>
<template v-else>
<ul>
<li v-for="line in detailed" :key="line.id" class="row">
<span>{{ line.name }} × {{ line.qty }}</span>
<span>{{ naira.format(line.subtotal) }}</span>
<button type="button" :aria-label="`Remove ${line.name}`" @click="basket.remove(line.id)">
Remove
</button>
</li>
</ul>
<p><strong>Total: {{ naira.format(total) }}</strong></p>
<button type="button" :disabled="status === 'sending'" @click="basket.checkout()">
{{ status === 'sending' ? 'Placing order…' : 'Place order' }}
</button>
<p v-if="status === 'error'" role="alert">Could not place the order: {{ error }}</p>
</template>
</template>
VUEStart the API in your first terminal and leave it running. The dev server restarts on its own when vite.config.ts changes:
node api/server.mjsCheck it worked
In your third terminal, send an order for two notebooks through the Vite proxy:
curl -s -X POST http://localhost:5173/api/orders -H 'Content-Type: application/json' -d '{"lines":[{"id":1,"qty":2}]}' | grep -F '"total":3000'The grep passes the reply through only if it holds the server's total, so an error page from a broken proxy prints nothing. After half a second it prints {"orderId":1,"total":3000}, and the API terminal logs POST /api/orders.
In the browser, add a notebook, open the basket and click "Place order". The button reads "Placing order…" and is disabled for half a second, then the page says "Order 2 placed. Total charged: ₦1,500." (your curl order was number 1), the list is replaced by "Your basket is empty." and the header shows "Basket (0)". Now stop the API with Ctrl+C, add an item and try again: the basket stays as it was, with "Could not place the order:" and the reason in red. Start the API again before you go on.
Step 6 · Keep the basket across reloads
A store lives in memory, so a reload, or a phone browser dropping the tab to save memory, empties it. On low-end Android phones that happens often, and a shopper on prepaid data should not have to rebuild a basket after it. Save the lines to localStorage and read them back when the store is created.
Inside a setup store you can use watch as in a component. Watch lines with deep: true, so increasing a quantity inside a line also triggers a save. On load, check every saved line and drop anything that is not valid, because localStorage is plain text that an old version of your app, a browser extension or the user can change. Both reads and writes sit in try, since storage can be full or blocked in private browsing:
cat > src/stores/basket.ts <<'TS'
import { defineStore } from 'pinia'
import { computed, ref, watch } from 'vue'
import { findProduct } from '../products'
export type Line = { id: number; qty: number }
export type Order = { orderId: number; total: number }
export const STORAGE_KEY = 'vue-stall-basket'
function loadLines(): Line[] {
try {
const saved: unknown = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]')
if (!Array.isArray(saved)) return []
return saved.filter(
(line): line is Line =>
Number.isInteger(line?.id) &&
findProduct(line.id) !== undefined &&
Number.isInteger(line.qty) &&
line.qty > 0,
)
} catch {
return []
}
}
export const useBasketStore = defineStore('basket', () => {
const lines = ref<Line[]>(loadLines())
const status = ref<'idle' | 'sending' | 'error'>('idle')
const error = ref('')
const lastOrder = ref<Order | null>(null)
watch(
lines,
(value) => {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(value))
} catch {
// Storage is full or blocked: the basket still works for this visit.
}
},
{ deep: true },
)
const detailed = computed(() =>
lines.value.flatMap((line) => {
const product = findProduct(line.id)
return product ? [{ ...line, name: product.name, subtotal: product.price * line.qty }] : []
}),
)
const count = computed(() => lines.value.reduce((sum, line) => sum + line.qty, 0))
const total = computed(() => detailed.value.reduce((sum, line) => sum + line.subtotal, 0))
function add(id: number) {
const line = lines.value.find((l) => l.id === id)
if (line) line.qty++
else lines.value.push({ id, qty: 1 })
lastOrder.value = null
}
function remove(id: number) {
lines.value = lines.value.filter((l) => l.id !== id)
}
function quantityOf(id: number) {
return lines.value.find((l) => l.id === id)?.qty ?? 0
}
async function checkout() {
if (lines.value.length === 0 || status.value === 'sending') return
status.value = 'sending'
error.value = ''
try {
const res = await fetch('/api/orders', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ lines: lines.value }),
})
const body = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(body.error ?? `HTTP ${res.status}`)
lastOrder.value = body as Order
lines.value = []
status.value = 'idle'
} catch (err) {
error.value = err instanceof Error ? err.message : String(err)
status.value = 'error'
}
}
return { lines, status, error, lastOrder, detailed, count, total, add, remove, quantityOf, checkout }
})
TSOnly the lines are saved. Status, errors and the last order belong to this visit, and prices are always looked up fresh from the product list.
Check it worked
Open http://localhost:5173/products/4, add the power bank and reload the page: the header still reads "Basket (1)" and the page says "In your basket: 1". In developer tools, under Application (Chrome, Edge) or Storage (Firefox), Local Storage for localhost:5173 holds the key vue-stall-basket with the value [{"id":4,"qty":1}]. Change that value to {broken and reload: the app starts with an empty basket instead of a blank page.
Step 7 · Test the store with Vitest
A store is plain TypeScript, so you can test it without mounting a component. Each test calls setActivePinia(createPinia()), which gives it a fresh Pinia, so no state leaks from one test to the next. The comment on the first line runs this file in jsdom, a browser-like environment with localStorage. fetch is replaced with a mock, so the tests never need the API:
mkdir -p src/stores/__tests__
cat > src/stores/__tests__/basket.spec.ts <<'TS'
// @vitest-environment jsdom
import { createPinia, setActivePinia } from 'pinia'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTick } from 'vue'
import { STORAGE_KEY, useBasketStore } from '../basket'
beforeEach(() => {
localStorage.clear()
setActivePinia(createPinia())
})
afterEach(() => {
vi.unstubAllGlobals()
})
describe('basket store', () => {
it('adds items and works out the count and total', () => {
const basket = useBasketStore()
basket.add(1)
basket.add(1)
basket.add(3)
expect(basket.quantityOf(1)).toBe(2)
expect(basket.count).toBe(3)
expect(basket.total).toBe(15000)
})
it('removes a whole line', () => {
const basket = useBasketStore()
basket.add(1)
basket.add(2)
basket.remove(1)
expect(basket.lines).toEqual([{ id: 2, qty: 1 }])
})
it('sends the lines and empties the basket when the order is accepted', async () => {
const fetchMock = vi.fn(async () =>
new Response(JSON.stringify({ orderId: 7, total: 1500 }), { status: 201 }),
)
vi.stubGlobal('fetch', fetchMock)
const basket = useBasketStore()
basket.add(1)
await basket.checkout()
expect(fetchMock).toHaveBeenCalledOnce()
expect(fetchMock).toHaveBeenCalledWith(
'/api/orders',
expect.objectContaining({ method: 'POST', body: JSON.stringify({ lines: [{ id: 1, qty: 1 }] }) }),
)
expect(basket.lastOrder).toEqual({ orderId: 7, total: 1500 })
expect(basket.count).toBe(0)
expect(basket.status).toBe('idle')
})
it('keeps the basket and reports the error when the request fails', async () => {
vi.stubGlobal('fetch', vi.fn(async () => { throw new TypeError('Failed to fetch') }))
const basket = useBasketStore()
basket.add(2)
await basket.checkout()
expect(basket.status).toBe('error')
expect(basket.error).toBe('Failed to fetch')
expect(basket.count).toBe(1)
})
it('saves the basket and restores it in a new Pinia', async () => {
useBasketStore().add(4)
await nextTick()
expect(localStorage.getItem(STORAGE_KEY)).toBe('[{"id":4,"qty":1}]')
setActivePinia(createPinia())
expect(useBasketStore().quantityOf(4)).toBe(1)
})
it('ignores a damaged or invalid saved basket', () => {
localStorage.setItem(STORAGE_KEY, '[{"id":99,"qty":1},{"id":2,"qty":-3},{"id":3,"qty":2}]')
expect(useBasketStore().lines).toEqual([{ id: 3, qty: 2 }])
setActivePinia(createPinia())
localStorage.setItem(STORAGE_KEY, '{broken')
expect(useBasketStore().lines).toEqual([])
})
})
TSThe await nextTick() in the save test is there because watch callbacks run just after the change, not during it.
npm testCheck it worked
Vitest reports one test file, src/stores/__tests__/basket.spec.ts, and ends with Tests 6 passed (6). To see a test catch a bug, change line.qty++ to line.qty += 2 in add, run npm test again and watch "adds items and works out the count and total" fail, then change it back.
Step 8 · Build for production and clean up
npm run build type-checks the project with vue-tsc and then bundles it. Stop the dev server in its terminal with Ctrl+C first:
npm run buildPreview the build in the second terminal. The preview server uses the same proxy to the API:
npm run previewOpen http://localhost:4173/, add something and place an order. When you are done, stop the preview and the API with Ctrl+C in their terminals, and delete the project:
cd ~
rm -rf ~/vue-stallCheck it worked
npm run build reports no type errors and ends with built in and a time. The list of files in dist/assets/ includes a separate small BasketView JavaScript file: that is the lazily loaded route. The preview behaves like the dev server, including a basket kept across reloads.
Next steps
- Go back over
ref,computed, props and events if any of the component code felt new: build your first Vue 3.5 app with the Composition API. - Render the same kind of pages on the server, with stores that work across server and browser: build a server-rendered site with Nuxt 4.
- Compare how React solves the same basket problem without a library: share state across React components with context and useReducer.
- Test components as well as stores, through what the user sees: test React components with Vitest and Testing Library.
Related tutorials
- Build your first Vue 3.5 app with the Composition APIYou will scaffold a Vue 3.5 and TypeScript project with create-vue, build a reading-list app with ref, computed, v-model, v-for, v-if, props and emitted events, then build it for production and check the result with vite preview.
- Build a server-rendered site with Nuxt 4You will build a server-rendered events listing with Nuxt 4.6, with file-based pages, a shared layout, data loaded through useFetch and useAsyncData, a JSON API in server/api, page titles from useSeoMeta, and a production build running as a plain Node.js server.
- Share state across React components with context and useReducerYou will turn a prop-drilled shopping basket into a reducer with named actions, share it through two React contexts and a useBasket hook, prove the add buttons stop re-rendering, and test the reducer as a plain function.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials