Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Store

Build your first Pinia store step by step with defineStore, state, getters and actions, then use it in components and learn how the id and the use function work.

You know what a store is and how to install Pinia. Now you will write one. By the end of this lesson you will have built a to-do store from scratch, understood every argument of defineStore, and seen how components use it.

defineStore in one picture

defineStore takes two things: a unique id and a definition. It returns a function, by convention named useXxxStore, that gives you the store.

JavaScript
import { defineStore } from "pinia";

export const useTodoStore = defineStore("todos", {
  state: () => ({ /* data */ }),
  getters: { /* derived values */ },
  actions: { /* functions */ },
});
flowchart LR
    A["defineStore('todos', {...})"] --> B["useTodoStore (a function)"]
    B -->|"first call"| C["creates the store<br/>inside the pinia"]
    B -->|"later calls"| D["returns the same store"]

defineStore does not create the store. It returns a function that creates the store on first use.

The id ("todos") must be unique in the app. Pinia uses it to register the store in the pinia container and to label it in Vue DevTools. Two stores with the same id would overwrite each other, so choose short, descriptive names.

Step 1: state

state is a function that returns an object. It must be a function so that every app (and every server request) gets a fresh copy instead of sharing one mutable object.

JavaScript
state: () => ({
  items: [],
  filter: "all",
}),

Everything you return becomes reactive. Reading store.items in a template tracks a dependency, and changing it re-renders.

Step 2: getters

Getters calculate values from state. They are cached and re-run only when the state they read changes, just like computed. Each getter receives the state as its first parameter:

JavaScript
getters: {
  remaining: (state) => state.items.filter((item) => !item.done).length,
},

Step 3: actions

Actions are plain functions. Inside them, this is the store, so you read and write state with this.items. Use regular function syntax or method shorthand in actions; arrow functions would lose this.

JavaScript
actions: {
  add(text) {
    this.items.push({ id: Date.now(), text, done: false });
  },
  toggle(id) {
    const item = this.items.find((entry) => entry.id === id);
    if (item) item.done = !item.done;
  },
},

Putting it together

Here is the complete store with a small interface. The component uses useTodoStore() inside setup(). Add a few tasks and toggle them.

A to-do store

Notice what the component does not contain: no arrays of tasks, no counting logic. The store owns data and rules, and the component only shows them and calls actions.

Using the store in a component

The useTodoStore() call returns the store, which is a reactive object. State, getters and actions are all properties of it:

JavaScript
const todos = useTodoStore();

todos.items;        // state
todos.remaining;    // getter
todos.add("Write"); // action

Two rules to remember:

  1. Do not destructure the store: const { items } = todos copies the value and loses reactivity. The next lesson group shows storeToRefs as the fix. See State Basics and storeToRefs.
  2. Call useTodoStore() where a pinia is active: inside setup(), <script setup>, or an action. A call at the top of a module may run too early.

You can call useTodoStore() in as many components as you like. They all get the same object:

Same object everywhere

store.$id returns the id you passed to defineStore. Properties that start with $ are built-in store helpers, and you will meet $patch, $reset, $subscribe and $onAction later in the course.

The id and the export name

The id and the exported function name are independent, but keep them related: id "todos", function useTodoStore. Pinia also lets you pass the id as the first argument and a setup function as the second, which is the setup store syntax. The store you wrote here is an options store because the definition is an options object.

You may also see defineStore({ id: "todos", state: ... }), a form where the id is inside the options. It still works, but the two-argument form is the one the documentation recommends.

Common beginner mistakes

  • State as an object, not a function. state: { count: 0 } is wrong. Always state: () => ({ count: 0 }).
  • Arrow function actions. add: (text) => { this.items... } fails because this is not the store. Use method shorthand.
  • Forgetting to return the object from the state arrow function without parentheses: () => { count: 0 } returns undefined because the braces are a block. Wrap the object in parentheses.
  • Duplicate ids. Two stores called "cart" silently conflict.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does defineStore return?

    defineStore returns a use function. The store is created lazily the first time you call it.
  2. 2. Why must state be a function?

    A function returns a new object every time, which prevents sharing mutable state between apps and requests.
  3. 3. Inside an action, what is this?

    In an action defined as a normal method, this is the store, so this.items reads and writes state.
  4. 4. What does store.$id return?

    $id is the unique id you gave the store, such as todos.

Summary

  • defineStore(id, definition) returns a useXxxStore function.
  • state is a function returning an object; getters are cached derived values; actions are methods where this is the store.
  • Calling the use function in any component returns the same store object.
  • Do not destructure the store, and call it where a pinia is active.
  • store.$id and other $ properties are built-in helpers.

Next: Pinia vs Vuex and Other Options