Skip to content

TIL: How to reset all stores in Pinia

An easy way to reset all the stores in your app.

2 min read

I just learned that every Pinia store has a $reset function.

To reset all in-use stores you just need to:

TypeScript
import { getActivePinia } from 'pinia'
const pinia = getActivePinia()
pinia._s.forEach((store) => store.$reset())

: https://stackoverflow.com/questions/71690883/pinia-reset-alternative-when-using-setup-syntax "Pinia: $reset alternative when using setup syntax" -->

Helper utility

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:

src/utils/useResetStore.ts
import { Pinia, Store, getActivePinia } 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 resetStore: Record<string, () => void> = {}
pinia._s.forEach((store, name) => {
resetStore[name] = () => store.$reset()
})
resetStore.all = () => pinia._s.forEach((store) => store.$reset())
return resetStore
}

Suppose we have defined and used app, user and auth stores.
Use it like this:

HTML
<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.

References

More notes connected by topic, not algorithmic noise.