From ba2b79eee1e4a33a51ac162fd37aecebed76d2e0 Mon Sep 17 00:00:00 2001 From: "Quang Tran (Chop Tr)" Date: Thu, 19 May 2022 17:20:36 +0700 Subject: [PATCH] Usecase for function style in defineStore --- .../docs/cookbook/create-store-dynamically.md | 46 +++++++++++++++++++ packages/docs/cookbook/index.md | 1 + 2 files changed, 47 insertions(+) create mode 100644 packages/docs/cookbook/create-store-dynamically.md diff --git a/packages/docs/cookbook/create-store-dynamically.md b/packages/docs/cookbook/create-store-dynamically.md new file mode 100644 index 0000000000..71de7b3269 --- /dev/null +++ b/packages/docs/cookbook/create-store-dynamically.md @@ -0,0 +1,46 @@ +# Create Store Dynamically + +Store can be created dynamically using factory pattern. Which will greatly help reduce boilerplate and structure your application. + +## Example + +An usecase of multiple tables that require pagination and filter. And all need to have separate stores to keep track of the result and pagings. + +We can have a creator function like this + +```js +export const createPagingStore = (endpoint) => { + const currentPage = ref(0) + const totalPage = ref(0) + const tableContent = ref() + const fetchData = async (page) => { + const data = await api.get(`https://example.com/${endpoint}?page=${page}`) + currentPage.value = page + totalPage.value = data.totalPage + tableContent = data.content + } + + return {currentPage, totalPage, tableContent, fetchData} +} +``` + +Inside the `defineStore` option function you will have access to all the state and actions, and extra logic as needed. + +```js + +export const usePagingWeather = defineStore('pagingWeather, () => { + const pagingStore = createPagingStore('weather') + + // Extra logics for this store + const sundays = computed(() => { + return pagingStore.tableContent.days.filter(day === 'sunday') + }) + + return { + ...pagingStore, + sundays, + } +}) +``` + +Don't worry about the same `ref`'s inside multiple store to be the same. They are handled by `pinia` as separate states in the stores. diff --git a/packages/docs/cookbook/index.md b/packages/docs/cookbook/index.md index 0bdf9a5e36..2f7d1edd23 100644 --- a/packages/docs/cookbook/index.md +++ b/packages/docs/cookbook/index.md @@ -4,5 +4,6 @@ - [HMR](./hot-module-replacement.md): How to activate hot module replacement and improve the developer experience. - [Testing Stores (WIP)](./testing.md): How to unit test Stores and mock them in component unit tests. - [Composing Stores](./composing-stores.md): How to cross use multiple stores. e.g. using the user store in the cart store. +- [Create Store Dynamically](./create-store-dynamically.md): An advance usecase for creating store. - [Options API](./options-api.md): How to use Pinia without the composition API, outside of `setup()`. - [Migrating from 0.0.7](./migration-0-0-7.md): A migration guide with more examples than the changelog.