Skip to content

Instantly share code, notes, and snippets.

@IlCallo
Last active January 13, 2023 18:17
Show Gist options
  • Save IlCallo/e01468917d7b79acf5f5fc1ab4f253b9 to your computer and use it in GitHub Desktop.
Save IlCallo/e01468917d7b79acf5f5fc1ab4f253b9 to your computer and use it in GitHub Desktop.
Global reactive store based on Composition API refs
// src/services/books.ts
// $fetch is a custom fetch wrapper performing common operations, we plan to release it as open source when we'll have time
// Should be easy to understand what it does
type Book = {
id: number;
title: string;
isbn: string;
price: number;
};
type BookData = {
title: string;
isbn: string;
price: number;
};
const books = ref<Book[]>([]);
export function useBookService() {
const getAll = () =>
$fetch('/books', {
method: 'GET',
onSuccess: (jsonData) => (books.value = jsonData),
});
const create = (bookData: BookData) =>
$fetch('/books', {
method: 'POST',
data: bookData,
});
const destroy = (bookId: number) =>
$fetch(`/books/${bookId}`, {
method: 'DELETE',
onSuccess: () => {
const deletedBookIndex = findIndex(books.value, ['id', bookId]);
deletedBookIndex !== -1 && books.value.splice(deletedBookIndex, 1);
},
});
return {
books,
getAll,
create,
destroy,
};
}
// src/pages/bookshelf.vue
<script>
import { defineComponent } from "vue";
import { useBookService } from "src/services/books";
export default defineComponent({
name: 'PageBookshelf',
setup() {
const { books, getAll: getBooks } = useBookService();
onMounted(getBooks);
return { books };
}
});
</script>
<template>
<div>
<q-list>
<q-item v-for="book in books" :key="book.id">{{ book.title }}</q-item>
</q-list>
</div>
</template>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment