Vue.js course ยท Module 11: Pinia
Actions in Pinia
In this lesson4
Actions are functions that modify state and perform operations - like NOVA LAB mission control commands. This is where business logic lives: fetching data, validation, error handling.
Basic Actions
In Composition API, actions are regular functions:
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useCrewStore = defineStore('crew', () => {
const members = ref([])
const selectedMember = ref(null)
// Simple action
function selectMember(member) {
selectedMember.value = member
}
// Action with logic
function addMember(member) {
if (members.value.length >= 8) {
throw new Error('Maximum crew size reached!')
}
members.value.push({
...member,
id: Date.now(),
joinedAt: new Date()
})
}
function removeMember(id) {
members.value = members.value.filter(m => m.id !== id)
if (selectedMember.value?.id === id) {
selectedMember.value = null
}
}
return { members, selectedMember, selectMember, addMember, removeMember }
})Asynchronous Actions
Actions can be asynchronous - ideal for fetching data from an API:
export const useCrewStore = defineStore('crew', () => {
const members = ref([])
const isLoading = ref(false)
const error = ref(null)
async function fetchCrew() {
isLoading.value = true
error.value = null
try {
const response = await fetch('/api/crew')
if (!response.ok) {
throw new Error('Failed to fetch crew data')
}
members.value = await response.json()
} catch (e) {
error.value = e.message
} finally {
isLoading.value = false
}
}
async function updateMemberRole(id, newRole) {
try {
const response = await fetch(`/api/crew/${id}`, {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ role: newRole })
})
if (!response.ok) throw new Error('Update failed')
const updated = await response.json()
const index = members.value.findIndex(m => m.id === id)
if (index !== -1) {
members.value[index] = updated
}
} catch (e) {
error.value = e.message
throw e
}
}
return { members, isLoading, error, fetchCrew, updateMemberRole }
})Error Handling in Actions
The try/catch/finally pattern is standard in asynchronous actions:
async function saveData(data) {
isLoading.value = true
error.value = null
try {
const result = await apiCall(data)
// Success - update state
items.value.push(result)
return result
} catch (e) {
// Error - save message
error.value = e.message
throw e // Pass error to component
} finally {
// Always - disable loading
isLoading.value = false
}
}Calling Actions from a Component
<script setup>
import { onMounted } from 'vue'
import { useCrewStore } from '@/stores/crew'
const crewStore = useCrewStore()
// Call on mount
onMounted(() => {
crewStore.fetchCrew()
})
// Handler with error handling
async function handleAddMember(member) {
try {
await crewStore.addMember(member)
} catch (e) {
alert('Error: ' + e.message)
}
}
</script>Code for this lesson: App.vue
<script setup>
import { ref, computed } from 'vue'
// Crew Store simulation with actions
const members = ref([
{ id: 1, name: 'Commander Nova', role: 'commander', status: 'active' },
{ id: 2, name: 'Engineer Atlas', role: 'engineer', status: 'active' },
{ id: 3, name: 'Scientist Darwin', role: 'scientist', status: 'resting' }
])
const isLoading = ref(false)
const error = ref(null)
const newName = ref('')
const newRole = ref('engineer')
// Getters
const activeMembers = computed(() =>
members.value.filter(m => m.status === 'active')
)
const crewCount = computed(() => members.value.length)
// Actions
async function fetchCrew() {
isLoading.value = true
error.value = null
try {
await new Promise(r => setTimeout(r, 1000))
members.value.push({
id: Date.now(),
name: 'Dr. Mars ' + Math.floor(Math.random() * 100),
role: 'scientist',
status: 'active'
})
} catch (e) {
error.value = e.message
} finally {
isLoading.value = false
}
}
function addMember() {
if (!newName.value.trim()) {
error.value = 'Name is required'
return
}
if (members.value.length >= 8) {
error.value = 'Maximum crew size (8) reached!'
return
}
error.value = null
members.value.push({
id: Date.now(),
name: newName.value,
role: newRole.value,
status: 'active'
})
newName.value = ''
}
function removeMember(id) {
members.value = members.value.filter(m => m.id !== id)
}
function toggleStatus(id) {
const member = members.value.find(m => m.id === id)
if (member) {
member.status = member.status === 'active' ? 'resting' : 'active'
}
}
</script>
<template>
<div class="nova-lab">
<h1>NOVA LAB - Actions Demo</h1>
<div class="stats">
<span>Crew: {{ crewCount }}/8</span>
<span>Active: {{ activeMembers.length }}</span>
</div>
<div class="add-form">
<input v-model="newName" placeholder="Member name..." class="input" />
<select v-model="newRole" class="input">
<option value="commander">Commander</option>
<option value="engineer">Engineer</option>
<option value="scientist">Scientist</option>
</select>
<button @click="addMember" class="btn">Add Member</button>
<button @click="fetchCrew" :disabled="isLoading" class="btn btn-alt">
{{ isLoading ? 'Loading...' : 'Fetch From API' }}
</button>
</div>
<div v-if="error" class="error">{{ error }}</div>
<div class="crew-list">
<div v-for="member in members" :key="member.id"
class="crew-card" :class="member.status">
<div class="crew-info">
<strong>{{ member.name }}</strong>
<span class="role">{{ member.role }}</span>
<span class="status-badge">{{ member.status }}</span>
</div>
<div class="crew-actions">
<button @click="toggleStatus(member.id)" class="btn-sm">
{{ member.status === 'active' ? 'Rest' : 'Activate' }}
</button>
<button @click="removeMember(member.id)" class="btn-sm btn-danger">
Remove
</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
.nova-lab {
background: #0a0e27;
color: #00ff88;
min-height: 100vh;
padding: 20px;
font-family: monospace;
}
h1 { color: #00ff88; margin-bottom: 15px; text-align: center; }
.stats { text-align: center; margin-bottom: 15px; color: #00b4d8; }
.stats span { margin: 0 10px; }
.add-form { display: flex; gap: 8px; margin-bottom: 15px; flex-wrap: wrap; max-width: 600px; margin: 0 auto 15px; }
.input {
background: #0a0e27;
border: 2px solid #00b4d8;
color: #00ff88;
padding: 8px;
font-family: monospace;
flex: 1;
min-width: 120px;
}
.btn {
background: #00b4d8;
color: #0a0e27;
border: none;
padding: 8px 16px;
cursor: pointer;
font-family: monospace;
font-weight: bold;
}
.btn:hover { background: #00ff88; }
.btn:disabled { opacity: 0.5; cursor: not-allowed; }
.btn-alt { background: #00ff88; }
.error {
background: rgba(255, 68, 68, 0.1);
border: 2px solid #ff4444;
color: #ff4444;
padding: 10px;
margin-bottom: 15px;
max-width: 600px;
margin: 0 auto 15px;
}
.crew-list { max-width: 600px; margin: 0 auto; }
.crew-card {
display: flex;
justify-content: space-between;
align-items: center;
padding: 12px;
margin-bottom: 8px;
border: 2px solid #00ff88;
background: rgba(0, 255, 136, 0.05);
flex-wrap: wrap;
gap: 8px;
}
.crew-card.resting { border-color: #ff9900; opacity: 0.7; }
.crew-info { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; }
.role { color: #00b4d8; }
.status-badge {
padding: 2px 8px;
font-size: 0.8em;
background: rgba(0, 255, 136, 0.2);
color: #00ff88;
}
.crew-card.resting .status-badge { background: rgba(255, 153, 0, 0.2); color: #ff9900; }
.crew-actions { display: flex; gap: 5px; }
.btn-sm {
background: #00b4d8;
color: #0a0e27;
border: none;
padding: 4px 10px;
cursor: pointer;
font-family: monospace;
font-size: 0.85em;
}
.btn-danger { background: #ff4444; color: #fff; }
</style>Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What are actions in Pinia?
2. How do you define an asynchronous action in Pinia?
These are 2 of 3 questions for this lesson. Solve the rest in the game.
Hands-on tasks in the game
- Code editor
Add an async action fetchCrew (try/catch/finally) and an action removeMember.
- Vertical ordering
Arrange the steps of the async action pattern
- Code editor
Create addMember with validation (max 4) and fetchWithError, which simulates an API error.
- Click in order
Arrange the elements to correctly use a store in a component
- Vertical ordering
Arrange the stages of the async action execution flow