How to Use State in Pinia for Vue 3: Simple Guide
In Pinia, you define state inside a store using a
state function that returns an object with your reactive data. You access and modify this state by importing the store and using its properties inside your Vue components.Syntax
To use state in Pinia, create a store with defineStore. Inside, define a state function that returns an object holding your data. This state is reactive and can be used in your components.
Parts explained:
defineStore: Creates a new store.state(): Returns an object with reactive properties.- Store ID: A unique string to identify the store.
javascript
import { defineStore } from 'pinia' export const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }) })
Example
This example shows a simple counter store with state and how to use it in a Vue component. The component displays the count and a button to increase it.
javascript
import { createApp } from 'vue' import { createPinia, defineStore } from 'pinia' // Define the store const useCounterStore = defineStore('counter', { state: () => ({ count: 0 }), actions: { increment() { this.count++ } } }) // Vue component const App = { template: ` <div> <p>Count: {{ counter.count }}</p> <button @click="counter.increment">Increase</button> </div> `, setup() { const counter = useCounterStore() return { counter } } } // Create app const app = createApp(App) app.use(createPinia()) app.mount('#app')
Output
Count: 0 (initially)
When clicking 'Increase', count increments by 1 each time.
Common Pitfalls
Common mistakes when using state in Pinia include:
- Defining
stateas an object instead of a function, which breaks reactivity. - Not calling the store inside
setup()or component context, causing undefined state. - Mutating state outside of actions or directly in components without using Pinia's reactive store.
javascript
/* Wrong: state as object (not function) */ export const useWrongStore = defineStore('wrong', { state: { count: 0 } }) /* Right: state as function */ export const useRightStore = defineStore('right', { state: () => ({ count: 0 }) })
Quick Reference
Remember these tips when using Pinia state:
- Always define
stateas a function returning an object. - Access the store inside Vue's
setup()or component context. - Use actions to modify state for better organization.
- Pinia state is reactive and updates your UI automatically.
Key Takeaways
Define Pinia state as a function returning an object for reactivity.
Use
defineStore to create stores with unique IDs.Access and modify state inside Vue components via the store instance.
Use actions to change state instead of direct mutations for clarity.
Always call the store inside
setup() or component context.