Blog>
Snippets

Using Selectors for Computed States

Exemplifies the creation and use of selectors in TanStack Store to compute derived state, enabling memoization for performance optimization.
import { defineStore } from 'pinia';

export const useTodosStore = defineStore('todos', {
  state: () => ({
    todos: []
  }),
  getters: {
    completedTodos: (state) => state.todos.filter(todo => todo.completed),
    todoCount: (state) => state.todos.length,
    completedCount: (state, getters) => getters.completedTodos.length
  }
});
Defines a store using Pinia with a state for 'todos'. It includes getters for computing derived states: 'completedTodos' for filtering completed todos, 'todoCount' for the total number of todos, and 'completedCount' that uses another getter to count the completed todos. This example shows how to use selectors for computed states in a store.
import { computed } from 'vue';
import { useTodosStore } from './stores/todos';

const todosStore = useTodosStore();

const completedTodosPercentage = computed(() => {
  if (todosStore.todoCount === 0) return 0;
  return (todosStore.completedCount / todosStore.todoCount) * 100;
});
Uses the Vue composition API to further compute a derived state: the percentage of completed todos. It demonstrates how to use computed properties in Vue components to create memoized selectors based on the store's state and getters, which is beneficial for performance optimization.