2022 / 09 / 24
2023 / 01 / 30
TIL: How to reset all stores in Pinia

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

frontend
vue 3
pinia

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())

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:

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:

<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