$reset for composition API stores #2543
-
|
In reference to #1012, the $reset method is not available on stores using the composition API. This solution on Stack overflow proposes an elegant way on how to do this using a plugin: We have build something similar as a Nuxt plugin: import type { Pinia, PiniaPluginContext, PiniaPlugin } from 'pinia'
import cloneDeep from 'lodash/cloneDeep'
const extendStoreMethods: PiniaPlugin = (context: PiniaPluginContext) => {
const { store } = context
const initialState = cloneDeep(store.$state)
const initialKeys = Object.keys(initialState)
store.$reset = () => {
store.$patch((state: Record<string, any>) => {
Object.keys(state).forEach((key) => {
if (initialKeys.includes(key)) {
state[key] = cloneDeep(initialState[key])
} else {
delete state[key]
}
})
})
store.$dispose()
}
}
export default defineNuxtPlugin((nuxtApp: any) => {
const pinia = nuxtApp.$pinia as Pinia
pinia.use(extendStoreMethods)
})Is there a reason why we should not use this? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
|
Depending on what's on the state (Classes, Dates, circular references) and the method used for cloning, this method might not always work. Calling the function
|
Beta Was this translation helpful? Give feedback.
Depending on what's on the state (Classes, Dates, circular references) and the method used for cloning, this method might not always work. Calling the function
state()like in option stores always works.$reset()is not that common to use. I personally never use it in my projects because I rarely need to reset a store. I might need to reset some values but rarely the whole store. But the real reason this is not in Pinia is to keep Pinia as lean as possible (1.5kb)