An easy way to reset all the stores in your app.
I just learned that every Pinia store has a $reset
function.
To reset all in-use stores you just need to:
import { getActivePinia } from 'pinia'
const pinia = getActivePinia()
pinia._s.forEach((store) => store.$reset())
Going a little further we can write a helper function that would let us reset all stores at once, or just a single one:
src/utils/useResetStore.ts
:
import { getActivePinia, Pinia, Store } from 'pinia'
interface ExtendedPinia extends Pinia {
_s: Map<string, Store>
}
export function useResetStore() {
const pinia = getActivePinia() as ExtendedPinia
if (!pinia) {
throw new Error('There is no active Pinia instance')
}
const resetStores: Record<string, () => void> = {}
pinia._s.forEach((store, name) => {
resetStores[name] = () => store.$reset()
})
resetStores.all = () => pinia._s.forEach((store) => store.$reset())
return resetStores
}
Suppose we have defined and used app
, user
and auth
stores.
Use it like this:
<script setup lang="ts">
import { useResetStore } from '@/utils/useResetStore'
const resetStore = useResetStore()
// Reset stores individually
resetStore.app()
resetStore.user()
resetStore.auth()
// Reset all stores
resetStore.all()
</script>
Note that Pinia doesn’t hold references to stores that have not been used yet.