Sobes.tech
Senior

In Pinia Composition API, there is no $reset method — how would you implement it?

sobes.tech AI

Answer from AI

In Pinia Composition API, you can implement a $reset method that resets the store's state to its initial value, preserving the original state when the store was created. For example:

import { defineStore } from 'pinia'
import { reactive } from 'vue'

export const useMyStore = defineStore('myStore', () => {
  const initialState = {
    count: 0,
    items: []
  }

  const state = reactive({ ...initialState })

  function reset() {
    Object.assign(state, initialState)
  }

  return { state, reset }
})

Here, initialState stores the original values, and the reset function restores them in the reactive store state.