Vue.js
Beginner
1 min read
Async Actions and Store Composition
Example
// src/stores/posts.ts
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useAuthStore } from './auth';
export const usePostsStore = defineStore('posts', () => {
const posts = ref([]);
const isLoading = ref(false);
const error = ref(null);
// Compose another store
const auth = useAuthStore();
async function fetchPosts() {
isLoading.value = true;
error.value = null;
try {
const res = await fetch('/api/posts', {
headers: { Authorization: `Bearer ${auth.token}` }
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
posts.value = await res.json();
} catch (e) {
error.value = e.message;
} finally {
isLoading.value = false;
}
}
async function createPost(payload) {
const res = await fetch('/api/posts', {
method: 'POST',
headers: { 'Content-Type': 'application/json',
Authorization: `Bearer ${auth.token}` },
body: JSON.stringify(payload),
});
const post = await res.json();
posts.value.unshift(post);
return post;
}
return { posts, isLoading, error, fetchPosts, createPost };
});