advanced
Async Actions in Pinia
Handle async operations like API calls in Pinia stores.
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
interface User {
id: number;
name: string;
email: string;
}
// Simulated API
async function fetchUsersApi(): Promise<User[]> {
await new Promise(r => setTimeout(r, 100))
return [
{ id: 1, name: 'Alice', email: 'alice@test.com' },
{ id: 2, name: 'Bob', email: 'bob@test.com' },
]
}
export const useUserStore = defineStore('users', () => {
const users = ref<User[]>([])
const isLoading = ref(false)
const error = ref<__________...>(null)
const userCount = computed(() => users.value.length)
const getUserById = computed(() => {
return (id: number) => users.value.__________...
})
__________... fetchUsers() {
isLoading.value = true
error.value = null
try {
users.value = __________...
} catch (e) {
error.value = (e as Error).message
} finally {
__________...
}
}
function clearUsers() {
users.value = []
error.value = null
}
return {
users,
isLoading,
error,
userCount,
getUserById,
fetchUsers,
clearUsers,
}
})0/5 filled tab moves · Ctrl+↵ submits · Ctrl+Shift+↵ runsstarter code