diff --git a/packages/docs/cookbook/create-store-dynamically.md b/packages/docs/cookbook/create-store-dynamically.md new file mode 100644 index 0000000000..6aa37d234b --- /dev/null +++ b/packages/docs/cookbook/create-store-dynamically.md @@ -0,0 +1,51 @@ +# 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 = (initialCurrentPage?: number) => { + const currentPage = ref(initialCurrentPage ?? 0) + const totalPage = ref(0) + + return { currentPage, totalPage } +} +``` + +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(1) + const content = ref() + + // Logics for this store + + const fetchData = async (page) => { + const data = await api.get(`https://example.com/?page=${page}`) + currentPage.value = page + totalPage.value = data.totalPage + content.value = data.content + } + + const sundays = computed(() => { + return pagingStore.content.value.days.filter(day === 'sunday') + }) + + return { + ...pagingStore, // currentPage, totalPage + fetchData, + content, + + 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.