Access $reset when using composition-style API? #1012
-
The composition-style API of Pinia has several advantages over the options-style API. One of them is the possibility to make the state readonly using Vue's Here's an example export const useMyStore = defineStore("myStore", () => {
const state = reactive({
foo : "Hello!"
})
const somePrivateAction = () => { ... }
const somePublicAction = () => { ... }
return {
...toRefs(readonly(state)), // state will be readonly outside of the store
somePublicAction // we did not return "somePrivateAction" so it won't be exposed
}
} Is it possible to access functions like export const useMyStore = defineStore("myStore", (/* some parameter containing $reset and $patch here*/) => {
...
} |
Beta Was this translation helpful? Give feedback.
Replies: 6 comments 2 replies
-
You can't access |
Beta Was this translation helpful? Give feedback.
-
Not sure if I should make a new discussion or not, but: I wonder what the best way would be to create a $reset for use in composition stores. Or should I not even try? Thanks for pointing me in the right direction. |
Beta Was this translation helpful? Give feedback.
-
The Setup Stores style needs to implement $reset $patch by itself. Here I think it is better to distinguish the two styles of APIs in the documentation. |
Beta Was this translation helpful? Give feedback.
-
The two APIs are supposed to offer the same functionality. But they clearly don't. |
Beta Was this translation helpful? Give feedback.
-
Any updates? My attempt: import * as actions from './actions'
import * as state from './state'
function withReset<T>(state: T) {
const _initState: any = {}
for (const key of Object.keys(state as any)) {
// Any value that is not a function
if (typeof (state as any)[key] !== 'function') {
const item = (state as any)[key]
_initState[key] = isRef(item) ? item.value : item
}
}
return {
...state,
_initState,
$reset() {
for (const key of Object.keys(this._state)) {
(this as any)[key] = this._initState[key]
// (this as any).$patch((state: any) => state[key] = this._initState[key])
}
}
}
}
export const useAuthStore = defineStore('auth', () => {
return withReset({
...state,
...actions,
})
}) Using the The line commented using This feels "dirty" to me, and I'm wondering why the discussion on this topic stopped. 🤔😔 |
Beta Was this translation helpful? Give feedback.
-
This could help : Pinia: How to reset stores created with function/setup syntax |
Beta Was this translation helpful? Give feedback.
You can't access
$patch()
because it is created after the creation of the store.$reset()
does only exist in option stores