Defining a store
Several components need the same data: a cart, the signed-in user, a theme.
Passing it down through props gets awkward, and provide / inject only reaches
a subtree. Pinia gives you a store: one reactive container that any component
can read and write.
You define a store with defineStore. It takes a unique id and an options object
holding state, getters, and actions:
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count += 1;
},
},
});
Two details matter. The id — 'counter' here — must be unique across the app; it
is how Pinia tells stores apart. And state is a function that returns the
initial state, not the state object itself, so each store instance starts fresh.
defineStore returns a function, conventionally named useCounterStore. You
call it to get the store instance. The name starts with use so it reads like
the composables it behaves like.
You are about to answer a short quiz on defining a store.