'Pinia: $reset alternative when using setup syntax
I have a pinia store created with setup syntax like:
defineStore('id', () => {
const counter = ref(0)
return { counter }
})
Everything has been working great with setup syntax because I can re-use other pinia stores.
Now, however, I see the need to re-use Pinia stores on other pages but their state needs to be reset.
In Vuex for example, I was using registerModule and unregisterModule to achieve having a fresh store.
So the question is: How to reset the pinia store with setup syntax?
Note: I know that I can do it manually by creating a function where you set all the state values to their initial ones
Note2: I found $dispose but it doesn't work. If $dispose is the answer, then how it works resetting the store between 2 components?
Solution 1:[1]
You can use a Pinia plugin that adds a $reset() function to all stores:
On the Pinia instance, call
use()with a function that receives astoreproperty. This function is a Pinia plugin.Deep-copy
store.$stateas the initial state. A utility likelodash.clonedeepis recommended for state that includes nested properties or complex data types, such asSet.Define
store.$reset()as a function that callsstore.$patch()with a deep-clone of the initial state from above. It's important to deep-clone the state again in order to remove references to the copy itself.
// store.js
import { createPinia } from 'pinia'
import cloneDeep from 'lodash.clonedeep'
const store = createPinia()
1??
store.use(({ store }) => {
2??
const initialState = cloneDeep(store.$state)
3??
store.$reset = () => store.$patch(cloneDeep(initialState))
})
Feel free to read the article based on this answer: How to reset stores created with function/setup syntax
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Roland |
