Pinia 04 ๐ Getters & Derived State โ Computing derived values, passing arguments to getters, and accessing other stores
Getters are the reactive “computed properties” of a Pinia store. Just as a Vue component uses computed properties to transform raw data into a display-ready format, a Pinia store uses getters to derive new state from existing state. Whether you need to filter a list, calculate a total price, or check if a user has specific permissions, getters provide a centralized, cached, and performant way to handle this logic. By moving data transformation out of the component and into the store, you ensure that the logic is reusable across the entire application and that your components remain focused on the user interface.
The power of getters lies in their efficiency. Because they are powered by Vueโs reactivity system, getters are cached based on their dependencies. If the underlying state does not change, the getter is not re-evaluated, even if it is accessed multiple times across different components. This makes them ideal for expensive operations like searching through large arrays or performing complex mathematical calculations. Furthermore, getters in Pinia are not limited to the local state of the store; they can interact with other getters within the same store or even pull data from entirely different stores, allowing for complex, cross-domain data dependencies.
This chapter explores the architectural role of getters and provides a deep dive into their implementation in both Option and Setup store styles. We will cover the mechanics of basic getters, the pattern for passing arguments to getters using functions, and the advanced technique of cross-store communication. We will also examine the nuances of caching and reactivity to ensure your derived state remains performant as your application grows in scale and complexity.
Key point: Getters are cached, reactive projections of the store’s state; they should never mutate state directly and are automatically re-evaluated only when their specific dependencies change.
Why exists
The Logic Duplication problem.
In large applications, multiple components often need the same piece of derived dataโsuch as a formatted user name or a filtered list of active tasks. Without getters, developers often find themselves copying the same logic into the computed section of every component. Getters solve this by providing a single “source of truth” for derived logic, ensuring that if the logic needs to change, it only needs to be updated in one place.
The Caching and Performance problem.
Performing complex calculations or filtering large datasets inside a component’s method or template is inefficient because it may trigger on every re-render. Getters utilize Vue’s caching mechanism, meaning they only recalculate when their specific state dependencies change. This “lazy evaluation” significantly boosts performance, especially in data-heavy dashboards or e-commerce lists.
The Component Bloat problem.
Components should ideally be thin layers that handle UI and user interaction. When a component contains dozens of lines of code dedicated to sorting, filtering, and mapping raw API data, it becomes difficult to read and maintain. Getters act as a clean API for the component, allowing it to request exactly what it needs (e.g., store.activeItems) without needing to know how that data is generated.
The Data Normalization problem.
Backend APIs often return data in formats that are optimized for storage rather than display. For example, dates might be ISO strings, and status codes might be integers. Getters provide a layer of data normalization, transforming raw backend data into human-readable strings or boolean flags before they ever reach the component.
The Cross-Domain Sync problem.
Modern apps are modular, with state split across different domains like Auth, Settings, and Products. Often, the state of one domain depends on another (e.g., showing prices in the user’s preferred currency). Getters allow stores to “talk” to each other, pulling in state from external stores to create a unified view of the application state without polluting the individual stores with redundant data.
a. Basic Getters: Option vs. Setup Stores
In an Option Store, getters are defined inside the getters object. Each getter function automatically receives the state as its first argument. This encourages a functional approach where you derive data directly from the state object.
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 1 }),
getters: {
// Basic getter receiving state
doubleCount: (state) => state.count * 2,
// Accessing other getters via 'this'
// Note: You must use a standard function, not an arrow function, to use 'this'
doubleCountPlusOne(): number {
return this.doubleCount + 1;
},
},
});
When using this to access other getters, you must explicitly define the return type if you are using TypeScript. This is because TypeScript’s inference can become circular or ambiguous when getters refer to each other.
In a Setup Store, getters are simply defined as computed() properties. This feels more natural to those already using the Composition API in their components.
import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
export const useCounterStore = defineStore('counter', () => {
const count = ref(1);
// Getter is just a standard Vue computed property
const doubleCount = computed(() => count.value * 2);
return { count, doubleCount };
});
The behavior is identical in both styles: the value is cached, reactive, and read-only. You cannot assign a value to a getter (e.g., store.doubleCount = 5 will fail).
b. Passing Arguments to Getters
Strictly speaking, getters do not accept arguments because they are properties, not functions. However, you can achieve this functionality by having a getter return a function. This is a common pattern when you need to find an item in a list by its ID or filter a list based on a dynamic criteria.
export const useUserStore = defineStore('users', {
state: () => ({
users: [
{ id: 1, name: 'Alice', active: true },
{ id: 2, name: 'Bob', active: false }
]
}),
getters: {
// Returns a function that takes an ID
getUserById: (state) => {
return (userId: number) => state.users.find((user) => user.id === userId);
},
},
});
Crucial Performance Note: When a getter returns a function, that getter is no longer cached. The function itself is cached, but every time you call that function in your component (e.g., store.getUserById(1)), the logic inside the function executes. If performance is a concern for a specific search, consider using a standard action or a localized computed property in the component.
<!-- Usage in Component -->
<script setup>
const userStore = useUserStore();
const user = userStore.getUserById(2); // Executes the search logic
</script>
c. Accessing Other Stores
One of Pinia’s most elegant features is the ability for getters to access data from other stores. To do this, you simply import and instantiate the other store inside the getter. Pinia ensures that these stores are correctly linked and reactive.
import { useAuthStore } from './authStore';
export const useCartStore = defineStore('cart', {
state: () => ({
items: []
}),
getters: {
// A getter that depends on the state of another store
summary(state) {
const auth = useAuthStore();
if (auth.isLoggedIn) {
return `Hello ${auth.userName}, you have ${state.items.length} items.`;
}
return 'Please log in to see your cart.';
},
},
});
This cross-store access is highly reactive. If the auth.userName changes in the AuthStore, the summary getter in the CartStore will automatically re-evaluate. This prevents you from having to manually sync data between stores or pass data around via actions.
In Setup Stores, the process is even more straightforward: just call the other store at the top of your setup function.
export const useCartStore = defineStore('cart', () => {
const items = ref([]);
const auth = useAuthStore(); // Instantited once
const summary = computed(() => {
return auth.isLoggedIn ? `Items: ${items.value.length}` : 'Log in';
});
return { items, summary };
});
Complete Example Session
// ============================================
// PART 1: THE AUTH STORE
// ============================================
export const useAuthStore = defineStore('auth', {
state: () => ({ user: { name: 'Eduardo', role: 'admin' } })
});
// ============================================
// PART 2: THE PRODUCT STORE (OPTION STYLE)
// ============================================
import { useAuthStore } from './auth';
export const useProductStore = defineStore('products', {
state: () => ({
items: [
{ id: 1, name: 'Phone', price: 500, stock: 5 },
{ id: 2, name: 'Laptop', price: 1000, stock: 0 }
],
taxRate: 0.1
}),
// ============================================
// PART 3: SIMPLE GETTER (STATE ACCESS)
// ============================================
getters: {
inStock: (state) => state.items.filter(i => i.stock > 0),
// ============================================
// PART 4: COMPOSED GETTER (THIS ACCESS)
// ============================================
totalStock(): number {
return this.inStock.reduce((total, item) => total + item.stock, 0);
},
// ============================================
// PART 5: PARAMETERIZED GETTER (RETURNS FN)
// ============================================
getProductById: (state) => {
return (id: number) => state.items.find(i => i.id === id);
},
// = ===========================================
// PART 6: CROSS-STORE GETTER
// = ===========================================
canManage(state) {
const auth = useAuthStore();
return auth.user.role === 'admin';
},
// ============================================
// PART 7: COMPLEX CALCULATION WITH CACHING
// ============================================
pricesWithTax: (state) => {
console.log('Calculating taxes...'); // Only logs when taxRate or items change
return state.items.map(i => i.price * (1 + state.taxRate));
}
}
});
// ============================================
// PART 8: USAGE IN COMPONENT
// ============================================
/*
<script setup>
const store = useProductStore();
// Accessing simple getter
const available = store.inStock;
// Accessing parameterized getter
const phone = store.getProductById(1);
</script>
*/
// ============================================
// PART 9: REACTIVITY TEST
// ============================================
// store.taxRate = 0.2; // triggers re-calculation of pricesWithTax
// ============================================
// PART 10: TYPESCRIPT RETURN HINT
// ============================================
// When using 'this', always provide the return type to help TS
// doubleCount(): number { return this.count * 2 }
The parts above cover the entire spectrum of getter functionality, from basic data derivation and getter composition to cross-store logic and handling dynamic arguments.
Quick Reference
Getter Syntax Comparison
| Feature | Option Store | Setup Store |
|---|---|---|
| Definition | Inside getters: {} object | Using computed(() => ...) |
| State Access | First argument (state) => ... | Variable access count.value |
| Other Getters | Using this.otherGetter | Variable access otherComputed.value |
| Cross Store | Instantiate inside getter | Instantiate at setup top |
Argument Passing Pattern
| Step | Action | Code Snippet |
|---|---|---|
| 1 | Define Getter | findItem: (state) => |
| 2 | Return Function | (id) => state.list.find(...) |
| 3 | Access | store.findItem(123) |
| 4 | Caching | Disabled for the inner logic |
Getter vs. Action vs. State
| Feature | State | Getter | Action |
|---|---|---|---|
| Writeable | Yes | No (Read-only) | N/A (Executes) |
| Cached | N/A | Yes | No |
| Async | No | No | Yes |
| Reactive | Yes | Yes | N/A |
Best Practices
โ Do This:
// Keep getters "pure" (no side effects or state mutations)
total: (state) => state.price * state.qty; // โ
// Provide return types when using 'this' for better TS support
double(): number { return this.count * 2; } // โ
// Use getters to keep your components clean and logical
const isFull = computed(() => cart.count >= cart.limit); // โ
// Use getters for expensive filtering logic to benefit from caching
filteredList: (state) => state.bigArray.filter(...); // โ
โ Don’t Do This:
// Don't mutate state inside a getter
wrong: (state) => { state.count++; return state.count; }; // โ
// Don't perform async operations (use actions instead)
asyncGetter: (state) => await fetch('/data'); // โ
// Don't use arrow functions if you need 'this'
double: (state) => this.count * 2; // 'this' is wrong context // โ
// Don't create a parameterized getter for simple logic
// (It kills caching; use a simple filter if possible) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Infinite Loop | Getter updates a state it depends on | Move mutation logic to an Action |
this is undefined | Arrow function used in Option Store getter | Use standard function declaration |
| TS Inference Error | Circular getter dependencies | Add explicit return types to getters |
| Caching not working | Returning a function (parameterized getter) | Only use if dynamic arguments are required |
| Stale Data | Forgetting to import the store in a getter | Call useOtherStore() inside the getter function |
| Value not updating | Destructuring the getter into a local variable | Use storeToRefs() or access via store.getter |
Real-World Examples
1. Checking Permissions
canEdit: (state) => state.user.role === 'admin' || state.user.isOwner
2. Formatting Currency
totalFormatted: (state) => `$${state.amount.toFixed(2)}`
3. Filtering Active Items
activeItems: (state) => state.items.filter(item => !item.archived)
4. Finding Item by ID (Parameterized)
getById: (state) => (id) => state.items.find(i => i.id === id)
5. Cross-Store Language Check
isTranslated: (state) => state.key && useLangStore().current === 'en'
6. Counting Search Results
resultCount: (state) => state.results.length
7. Composing Complex Logic
isPremiumUser(): boolean { return this.hasSubscription && this.isActive }
8. Normalizing API Data
userList: (state) => state.rawUsers.map(u => ({ label: u.name, value: u.id }))
9. Validating Form State
isValid: (state) => state.email.includes('@') && state.password.length > 8
10. Calculating Cart Subtotal
subtotal: (state) => state.cart.reduce((sum, i) => sum + i.price, 0)
Visual
The Caching Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ STORE STATE: [ count: 5 ] โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ (1. State changes)
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ GETTER EVALUATION (doubleCount) โ
โ Calculation: 5 * 2 = 10 โ
โโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ (2. Value cached: 10)
โผ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโ
โ Component A โ โ Component B โ โ Getter โ
โ Read value: 10 โ โ Read value: 10 โ โ Total โ
โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโ
(3. Subsequent reads do NOT trigger re-calculation)
Cross-Store Dependency Graph
โโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโ
โ AUTH STORE โ โ PREF STORE โ
โ [ user: 'Bob' ] โ โ [ lang: 'en' ] โ
โโโโโโโโโโโโฌโโโโโโโโโโโโ โโโโโโโโโโโโฌโโโโโโโโโโโโ
โ โ
โโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ DASHBOARD STORE โ
โ Getter: greeting โ
โ Result: "Hello Bob (EN)" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
(Greeting updates if EITHER Auth or Pref changes)
Parameterized Getter (No Caching)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Getter: getUserById(id) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Call(1): Scan array... Found! (Execution happens) โ
โ Call(2): Scan array... Found! (Execution happens) โ
โ Call(1): Scan array... Found! (Execution happens again) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
(Because the return is a NEW function each time,
Pinia cannot cache the internal result of the call)
Summary
| Item | Value |
|---|---|
| Purpose | Derive state from raw data |
| Reactivity Type | Computed / Read-only |
| Caching | Enabled (Lazy evaluation) |
| Async Support | No (Use actions) |
| State Access | state param or this |
| Argument Pattern | Function returning a function |
| Cross-Store | Import/Instantiate inside getter |
| Best Location | Shared logic across components |
Key takeaways:
- Getters are performance-optimized. They only recalculate when their specific state dependencies change, making them much faster than calling methods in templates .
- They act as the “API” of your data. By using getters, you provide components with ready-to-use data rather than forcing them to handle raw structures .
thisvsstatein Option Stores. Use thestateargument for basic derivation andthiswhen you need to access other getters in the same store .- Parameterized getters are dynamic but uncached. Returning a function from a getter allows you to pass arguments (like an ID), but be aware that the internal logic will run on every call .
- Cross-store integration is native. You can seamlessly pull state from other Pinia stores inside a getter, creating complex reactive chains across your application .
- They must be pure. Never modify state or trigger side effects inside a getter; they should be strictly for calculating a return value based on inputs .
Remember: Think of getters as the lenses through which your components view the store’s state. Use them to sort, filter, and format data so that your components stay simple and your business logic remains centralized and efficient.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!