Skip to content
intermediate

Define a Pinia Store

Create a Pinia store using the Composition API setup syntax.

import { __________... } from 'pinia'
import { ref, computed } from 'vue'

interface Todo {
  id: number;
  text: string;
  completed: boolean;
}

export const useTodoStore = defineStore('todos', () => {
  const todos = __________...
  let nextId = 1

  const completedTodos = computed(() => {
    return todos.value.__________...
  })

  const pendingTodos = computed(() => {
    return todos.value.filter((todo) => !todo.completed)
  })

  const totalCount = computed(() => todos.value.length)

  function addTodo(text: string) {
    todos.value.push({
      id: nextId++,
      text,
      __________...,
    })
  }

  function toggleTodo(id: number) {
    const todo = todos.value.find((t) => t.id === id)
    if (todo) {
      __________...
    }
  }

  function removeTodo(id: number) {
    const index = todos.value.findIndex((t) => t.id === id)
    if (index > -1) {
      todos.value.splice(index, 1)
    }
  }

  return {
    todos,
    completedTodos,
    pendingTodos,
    totalCount,
    addTodo,
    toggleTodo,
    removeTodo,
  }
})
0/5 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code