March 26th, 2023
Reset Pinia Store not working in composition script setup store? Learn how to reset pinia store, state in options store setup (with $reset), and in composition script setup store (manually). Sometimes you have to reset Pinia store to its initial values, for example:
If a user logs out and you don't reset pinia store to its initial values, the next authenticated user will see state values from previous authenticated user.
In Option Stores, you can reset the state to its initial value by calling the $reset()
method on the store:
1const dogStore = useStore()2 3dogStore.$reset()
In Script store, you have to manually create $reset function and set those values to initial values. Don't forget to return $reset function.
1// dogStore.js 2import { defineStore } from 'pinia' 3import { computed, ref } from 'vue' 4 5export const useDogStore = defineStore('dog', () => { 6 const dogs = ref(null); 7 const chosenDog = ref(null); 8 9 // ...10 11 function $reset() {12 dogs.value = null13 chosenDog.value = null14 }15 16 return { dogs, chosenDog, $reset }17})
in AuthenticatedLayout @click on Logout button also reset store, otherwise after another user logs in, it will show the state from previous user, not currently authenticated user.
1<DropdownLink @click="dogStore.$reset()" :href="route('logout')" method="post" as="button">2 Log Out3</DropdownLink>