0
0
Vueframework~30 mins

Type-safe stores with Pinia in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Type-safe stores with Pinia
📖 Scenario: You are building a simple Vue app to manage a list of tasks. You want to keep the tasks in a central store using Pinia. To avoid mistakes, you will make the store type-safe using TypeScript.
🎯 Goal: Create a Pinia store with TypeScript that holds a list of tasks. Each task has an id (number) and a title (string). Add a getter to count tasks and an action to add a new task.
📋 What You'll Learn
Create a Pinia store named useTaskStore using defineStore
Define a TypeScript interface Task with id: number and title: string
Store state as an array of Task objects named tasks
Add a getter taskCount returning the number of tasks
Add an action addTask that takes a Task and adds it to tasks
💡 Why This Matters
🌍 Real World
Type-safe stores help prevent bugs by ensuring data shapes are consistent. This is useful in any Vue app managing shared state.
💼 Career
Many Vue jobs require managing state with Pinia and TypeScript. Knowing how to create type-safe stores is a valuable skill.
Progress0 / 4 steps
1
Set up the Task interface and initial state
Create a TypeScript interface called Task with id as a number and title as a string. Then create a Pinia store named useTaskStore using defineStore with an empty array of tasks as the state.
Vue
Hint

Use interface Task { id: number; title: string } and state: () => ({ tasks: [] as Task[] }).

2
Add a getter to count tasks
Add a getter named taskCount inside useTaskStore that returns the length of the tasks array.
Vue
Hint

Use getters: { taskCount: (state) => state.tasks.length }.

3
Add an action to add a new task
Add an action named addTask inside useTaskStore that takes a parameter task of type Task and pushes it into the tasks array.
Vue
Hint

Use actions: { addTask(task: Task) { this.tasks.push(task) } }.

4
Export the store and use it in a Vue component
Ensure the store useTaskStore is exported. Then, in a Vue component, import useTaskStore and create a store instance by calling it inside setup().
Vue
Hint

Import useTaskStore and call it inside setup() to create taskStore.