Search code examples
vue.jsvuejs3vitepinia

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: The $reset() method is only implemented for stores defined with the object syntax, so that is not an option.

Note 2: I know that I can do it manually by creating a function where you set all the state values to their initial ones

Note 3: I found $dispose but it doesn't work. If $dispose is the answer, then how it works resetting the store between 2 components?


Solution

  • You can use a Pinia plugin that adds a $reset() function to all stores:

    1. On the Pinia instance, call use() with a function that receives a store property. This function is a Pinia plugin.

    2. Deep-copy store.$state as the initial state. A utility like lodash.clonedeep is recommended for state that includes nested properties or complex data types, such as Set.

    3. Define store.$reset() as a function that calls store.$patch() with a deep-clone of the initial state from above.

    4. We use Object.assign to make it work properly with objects see here. Same way pinia does itself when defining $reset for Options API.

    // 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($state => {
          4️⃣
          Object.assign($state, initialState)
        })
      }
    })
    

    demo


    Feel free to read the article based on this answer: How to reset stores created with function/setup syntax