Clear all stores #911
-
Hi! I'm trying to create a function / plugin to reset all stores, which is also described in #693. I'm using Nuxt, so this is my plugin: import { defineNuxtPlugin } from '@nuxtjs/composition-api'
import { Store } from 'pinia'
declare module 'pinia' {
export interface PiniaCustomProperties {
resetAllStores: () => void
}
}
let stores: Store[] = []
const resetAllStores = () => {
for (const store of stores) {
store.$reset()
}
stores = []
}
export default defineNuxtPlugin(({ $pinia }) => {
$pinia.use(({ store }) => {
stores.push(store)
})
$pinia.use(resetAllStores)
}) However, this leads to the following error:
I would expect that this function is always there, because I can run const store = useMyStore()
store.$reset() |
Beta Was this translation helpful? Give feedback.
Replies: 10 comments 18 replies
-
Any idea how to reset store in setup syntax? |
Beta Was this translation helpful? Give feedback.
-
That's how i reset all the stores:
import {
createPinia as crPinia, Pinia, StateTree,
} from 'pinia';
import serialize from 'serialize-javascript';
import user from './user';
import core from './core';
let pinia: Pinia;
let initialState: Record<string, StateTree>;
const useStore = {
user,
core,
};
export const setInitialState = (): void => {
const stores = Object.keys(useStore) as Array<keyof typeof useStore>;
stores.forEach((store) => {
useStore[store]();
});
initialState = JSON.parse(serialize(pinia.state.value));
console.log(initialState);
};
export const resetState = (): void => {
const stores = Object.keys(useStore) as Array<keyof typeof useStore>;
stores.forEach((store) => {
useStore[store](pinia).$state = initialState[store] as never;
});
};
export const createPinia = (): Pinia => {
pinia = crPinia();
return pinia;
};
export const usePinia = (): Pinia => pinia;
export default useStore; |
Beta Was this translation helpful? Give feedback.
-
Hi there, I've used this approach and it worked for me import { getActivePinia } from "pinia"
// map through that list and use the **$reset** fn to reset the state
getActivePinia()._s.forEach(store => store.$reset()); Note if there is a better way, please let me know |
Beta Was this translation helpful? Give feedback.
-
@mohamedaminefh I used a different way to iterate over the stores. And also made an example reusable function Hope it helps others too. ✌️ |
Beta Was this translation helpful? Give feedback.
-
Here's the latest functionality for reseting pinia stores with SSR support: // stores/plugins/resetStores.ts
import type {
PiniaPluginContext,
StateTree,
Store,
_ActionsTree,
_GettersTree,
} from "pinia";
declare const window: Window & {
INITIAL_STATE_FOR_RESET: Record<string, StateTree>;
};
type _Store = Store<string, StateTree, _GettersTree<StateTree>, _ActionsTree>;
export const state: Record<string, StateTree> = {};
export const stores: Record<string, _Store> = {};
if (!import.meta.env.SSR) {
Object.assign(state, window.INITIAL_STATE_FOR_RESET);
}
/**
* @description reset all registered stores in pinia.
* @returns void
*/
export function resetAll(): void {
Object.keys(stores).forEach((storeName) => {
stores[storeName].$patch(state[storeName]);
});
}
export function resetState({ store }: PiniaPluginContext): void {
if (import.meta.env.SSR) {
const initialState = JSON.parse(JSON.stringify(store.$state));
state[store.$id] = initialState;
stores[store.$id] = store;
store.$reset = () => store.$patch(JSON.parse(JSON.stringify(initialState)));
store.$resetAll = resetAll;
} else {
stores[store.$id] = store;
store.$reset = () =>
store.$patch(
state[store.$id] || JSON.parse(JSON.stringify(store.$state))
);
store.$resetAll = resetAll;
}
} // stores/index.ts
import { createPinia as crPinia } from "pinia";
import type { Pinia } from "pinia";
import { resetState, state } from "./plugins/resetStore";
let pinia: Pinia;
export const createPinia = (): { pinia: Pinia; ssrState: typeof state } => {
pinia = crPinia();
pinia.use(resetState);
return { pinia, ssrState: state };
};
export const usePinia = (): Pinia => pinia; |
Beta Was this translation helpful? Give feedback.
-
Hi
I don't see where you use _createPinia method. That method have to be the
first call before other store manipulation.
Dne čt 7. 7. 2022 3:18 uživatel Kurt ***@***.***> napsal:
… Hi, @darthf1 <https://github.com/darthf1>
I follow your steps code to create my store with resetState function, many
thanks for this.
I import resetState in my router file and use it in navigation guard, but
once I update my component, it will show error that say I can't access
store before initialization
following are my part of codes:
// store.ts
import { createPinia as _createPinia, StateTree, Pinia } from 'pinia'import piniaPluginPersist from 'pinia-plugin-persist'import { useUserStore } from './modules/user'import { useAppStore } from './modules/app'import { useTimeStore } from './modules/time'import { usePermissionStore } from './modules/permission'import { useSettingsStore } from './modules/settings'
let pinia: Pinialet initialState: Record<string, StateTree>
const useStore = {
useUserStore, // Error line here
useAppStore,
useTimeStore,
usePermissionStore,
useSettingsStore}...
// router.ts
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'import Home from '@/views/home'import FrontStageLayout from '@/views/frontstage'import BackStageLayout from '@/views/backstage'import NProgress from 'nprogress'import 'nprogress/nprogress.css'import { resetState } from '@/store' // Import resetState function here, and I got error while hmr
...
[image: 2022-07-07_09-18]
<https://user-images.githubusercontent.com/32745146/177668888-0959ed0a-2c7a-45e3-93e0-ba71a2a26b84.png>
I do not know how to fix it, have any idea for that?
—
Reply to this email directly, view it on GitHub
<#911 (reply in thread)>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/ACGRXEQMH25BXQZYWKUK3ATVSYV7XANCNFSM5KNT2ASA>
.
You are receiving this because you are subscribed to this thread.Message
ID: ***@***.***>
|
Beta Was this translation helpful? Give feedback.
-
I'm using this code: import { getActivePinia } from 'pinia';
export const resetAllPiniaStores = () => {
const activeStores = Object.keys(getActivePinia().state.value);
activeStores.forEach((store) => {
getActivePinia()._s.get(store).$reset();
});
}; followed by: import { resetAllPiniaStores } from '@/store/index';
const logout = async () => {
auth.logout();
await router.push({ name: 'login' });
resetAllPiniaStores();
}; |
Beta Was this translation helpful? Give feedback.
-
After looking at #1859 thank you @davidAtInleague import { Store } from "pinia";
const AllPiniaStores = new Set<Store>();
pinia.use(({ store }) => {
AllPiniaStores.add(store);
store.$all = AllPiniaStores;
store.$reset_all = () => store.$all.forEach((s) => s.$reset());
});
declare module "pinia" {
export interface PiniaCustomProperties {
$all: typeof AllPiniaStores;
/** Reset all the stores */
$reset_all: () => void;
}
} |
Beta Was this translation helpful? Give feedback.
-
if you don't care and don't mind about a page refresh. You could just use |
Beta Was this translation helpful? Give feedback.
-
this work and is less tricky i think
|
Beta Was this translation helpful? Give feedback.
Hi there, I've used this approach and it worked for me
Note
getActivePinia()
must be called afterapp.use(pinia)
and that in SSRs it must be called withinscript setup
or thesetup()
functionif there is a better way, please let me know