Skip to content

Commit

Permalink
Usecase for function style in defineStore
Browse files Browse the repository at this point in the history
  • Loading branch information
trchopan committed May 19, 2022
1 parent 5d44937 commit ba2b79e
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
46 changes: 46 additions & 0 deletions 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.
1 change: 1 addition & 0 deletions packages/docs/cookbook/index.md
Expand Up @@ -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.

0 comments on commit ba2b79e

Please sign in to comment.