Skip to content

Commit ba2b79e

Browse files
committed
Usecase for function style in defineStore
1 parent 5d44937 commit ba2b79e

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
# Create Store Dynamically
2+
3+
Store can be created dynamically using factory pattern. Which will greatly help reduce boilerplate and structure your application.
4+
5+
## Example
6+
7+
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.
8+
9+
We can have a creator function like this
10+
11+
```js
12+
export const createPagingStore = (endpoint) => {
13+
const currentPage = ref(0)
14+
const totalPage = ref(0)
15+
const tableContent = ref()
16+
const fetchData = async (page) => {
17+
const data = await api.get(`https://example.com/${endpoint}?page=${page}`)
18+
currentPage.value = page
19+
totalPage.value = data.totalPage
20+
tableContent = data.content
21+
}
22+
23+
return {currentPage, totalPage, tableContent, fetchData}
24+
}
25+
```
26+
27+
Inside the `defineStore` option function you will have access to all the state and actions, and extra logic as needed.
28+
29+
```js
30+
31+
export const usePagingWeather = defineStore('pagingWeather, () => {
32+
const pagingStore = createPagingStore('weather')
33+
34+
// Extra logics for this store
35+
const sundays = computed(() => {
36+
return pagingStore.tableContent.days.filter(day === 'sunday')
37+
})
38+
39+
return {
40+
...pagingStore,
41+
sundays,
42+
}
43+
})
44+
```
45+
46+
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.

packages/docs/cookbook/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,5 +4,6 @@
44
- [HMR](./hot-module-replacement.md): How to activate hot module replacement and improve the developer experience.
55
- [Testing Stores (WIP)](./testing.md): How to unit test Stores and mock them in component unit tests.
66
- [Composing Stores](./composing-stores.md): How to cross use multiple stores. e.g. using the user store in the cart store.
7+
- [Create Store Dynamically](./create-store-dynamically.md): An advance usecase for creating store.
78
- [Options API](./options-api.md): How to use Pinia without the composition API, outside of `setup()`.
89
- [Migrating from 0.0.7](./migration-0-0-7.md): A migration guide with more examples than the changelog.

0 commit comments

Comments
 (0)