Advanced Pinia — Vue

In a setup-style store, ref is state and computed is a getter, such as total, which adds up the prices in the items array with items.value.reduce(...). A…

In the previous lesson the cart store only counted count and total. A real cart keeps a list of dishes: each dish can be added and removed, the total is calculated from that list, and at the end of the day everything is emptied. This lesson completes the store: state as an array, a getter with computed, actions that add and remove, storeToRefs, $patch and $reset.

Picture the board on the kitchen wall at Mrs. Sri's stall again. Now each order is written on its own line. The total at the bottom is always added up again from those lines. One line can be crossed out. When the stall closes, the board is wiped clean, like it was in the morning. In the code, the board is the store, and each line is one item in the items array. The total is the total getter. Crossing out a line is the remove action, and wiping the board is the clear action.

A complete setup-style store

This is the complete cart store, written in the setup style (ref, computed and functions):

// stores/cart.js
import { ref, computed } from "vue"
import { defineStore } from "pinia"

export const useCartStore = defineStore("cart", () => {
  const items = ref([])
  const table = ref(null)
  let nextId = 0

  const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0))

  function add(menu) {
    items.value.push({ id: ++nextId, name: menu.name, price: menu.price })
  }
  function remove(index) {
    items.value.splice(index, 1)
  }
  function clear() {
    items.value = []
    table.value = null
  }

  return { items, table, total, add, remove, clear }
})

table holds the table number, and null means it isn't set yet. nextId is a plain variable, not a ref, because it's only used to make the id and is never shown. This table shows what the store holds after each action is called:

Event items total
start [] 0
add(Fried Rice) Fried Rice 15 15
add(Iced Tea) Fried Rice 15, Iced Tea 5 20
remove(0) Iced Tea 5 5
clear() [] 0

In the exercises, you use the real Pinia with a todo list. In the first exercise, you take todos from the store through storeToRefs, add the typed text through the addTodo action, then empty the field. In the second exercise, you complete an options-style store: a store written with a state, getters and actions object, like the first store in the previous lesson. You add a total getter and an action that removes one todo with splice(index, 1). Then the reset button calls $reset(), which brings back the two starting todos.

This is a component that uses the cart store above:

<script setup>
import { storeToRefs } from "pinia"
import { useCartStore } from "../stores/cart"

const cart = useCartStore()
const { items, total } = storeToRefs(cart)
const { remove } = cart
</script>

<template>
  <ul>
    <li v-for="(item, i) in items" :key="item.id">
      {{ item.name }} ${{ item.price }}
      <button @click="remove(i)">×</button>
    </li>
  </ul>
  <p>Total: ${{ total }}</p>
</template>

storeToRefs: state and getters become refs, actions are taken directly

The component above takes things out of the store in two ways:

Written What it holds
storeToRefs(cart) items, table, total: state and getters, all refs
const { remove } = cart the action, straight from the store

$patch and $reset

Every store has a few built-in methods whose names start with $. $patch changes several pieces of state at once, in two forms:

cart.$patch({ table: 4 })              // change several pieces of state at once

cart.$patch((state) => {              // the function form, handy for arrays
  state.items.push({ id: 99, name: "Iced Tea", price: 5 })
  state.table = 7
})

$reset() puts the state back to its starting values, but only in an options-style store. In that style, state is a function that returns the starting values, so Pinia can call state() again:

export const useCartStore = defineStore("cart", {
  state: () => ({ items: [], table: null }),
  getters: {
    total: (state) => state.items.reduce((sum, item) => sum + item.price, 0),
  },
})

cart.$reset()   // items: [], table: null, so total is 0

Now take a guess. The cart store at the start of this lesson is written in the setup style. If the code calls cart.$reset() when the stall closes, what happens to the cart's contents in the production build?

In the production build, $reset() does nothing: the cart's contents stay, because a setup-style store has no state() function to call again. In development mode, the code stops with this error instead:

🍍: Store "cart" is built using the setup syntax and does not implement $reset().

For a setup-style store, write your own action that empties the state, like clear() at the start of this lesson.

🎯 A store using another store

A store may call another store. For example, the cart refuses orders while the stall is closed. Whether the stall is open is kept in the stall store (useStallStore()), in its isOpen state:

export const useCartStore = defineStore("cart", () => {
  const stall = useStallStore()
  const items = ref([])

  function add(menu) {
    if (!stall.isOpen) return
    items.value.push({ ...menu })
  }

  return { items, add }
})

⚠️ Missteps when changing a list in a store

TL;DR: In a setup-style store, ref is state and computed is a getter, such as total, which adds up the prices in the items array with items.value.reduce(...). A function is an action. Inside an action, push adds an item to the array, and splice(index, 1) removes one item. storeToRefs() takes state and getters as refs, so they stay reactive after you take the store apart. Actions are taken straight from the store. $patch changes several pieces of state at once, through an object or a function. $reset() puts the state back to its starting values, but only in an options-style store (a store written with a state, getters, actions object). A setup-style store needs its own action that empties the state. A store may use another store inside its setup.

⚡ A getter and actions for a list

Write:

const total = computed(() => items.value.reduce((sum, item) => sum + item.price, 0))

function add(menu) {
  items.value.push({ id: ++nextId, name: menu.name, price: menu.price })
}
function remove(index) {
  items.value.splice(index, 1)
}

Meaning: In this setup-style store, items is a ref holding the array of dishes in the cart. nextId is a counter for each item's id. A computed is a getter: total is recalculated automatically from items, starting at 0. The add action uses push to add one dish to the array. The remove action uses splice(index, 1) to remove one item from the array.

⚡ storeToRefs for state, actions taken directly

Write:

const cart = useCartStore()
const { items, total } = storeToRefs(cart)
const { remove } = cart
Guess first: if you write const { remove } = storeToRefs(cart), does the button that calls remove work?

No. storeToRefs skips actions, so remove is undefined, and the button throws an error because remove isn't a function.

Meaning: cart is the store. storeToRefs() turns the state (items) and the getter (total) into refs that stay reactive after you take them out. Actions such as remove are taken from the store itself.

⚡ $reset only exists in the options style

Guess first: $reset() is a built-in store method that puts the state back to its starting values. The cart store is written in the setup style. If cart.$reset() is called in the production build, what happens to the cart's contents?

They stay. $reset() calls the state() function again to get the starting values. A setup-style store has no such function, so $reset() does nothing.

Meaning: $reset() only works in an options-style store, written with a state, getters and actions object. A setup-style store needs its own action that empties the state, like clear(), which fills items with an empty array again.

What you will learn