diff --git a/packages/pinia/__tests__/store.spec.ts b/packages/pinia/__tests__/store.spec.ts index 4e0a21ad7e..cef8262448 100644 --- a/packages/pinia/__tests__/store.spec.ts +++ b/packages/pinia/__tests__/store.spec.ts @@ -379,4 +379,16 @@ describe('Store', () => { `[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "anyName" in store "main".` ).toHaveBeenWarnedTimes(1) }) + + it('warns when creating store with existing id', async () => { + const storeId = 'testStoreID'; + const useFirstStore = defineStore(storeId, {}); + const useSecondStore = defineStore(storeId, {}); + useFirstStore(); + useSecondStore(); + + expect( + `[🍍]: Stores should have unique identifiers. Found multiple stores with id "testStoreID". Rename one of them.` + ).toHaveBeenWarned(); + }); }) diff --git a/packages/pinia/src/createPinia.ts b/packages/pinia/src/createPinia.ts index f71497fd31..90253bc3df 100644 --- a/packages/pinia/src/createPinia.ts +++ b/packages/pinia/src/createPinia.ts @@ -52,6 +52,7 @@ export function createPinia(): Pinia { _a: null, _e: scope, _s: new Map(), + _k: [], state, }) diff --git a/packages/pinia/src/rootStore.ts b/packages/pinia/src/rootStore.ts index 0509a5c8eb..9bbd3fa21e 100644 --- a/packages/pinia/src/rootStore.ts +++ b/packages/pinia/src/rootStore.ts @@ -85,6 +85,14 @@ export interface Pinia { */ _s: Map + /** + * Registry of store ids defined in this pinia instance. + * This is used to check for duplicated keys. + * + * @internal + */ + _k: Array + /** * Added by `createTestingPinia()` to bypass `useStore(pinia)`. * diff --git a/packages/pinia/src/store.ts b/packages/pinia/src/store.ts index 98d77a2666..4504ee2127 100644 --- a/packages/pinia/src/store.ts +++ b/packages/pinia/src/store.ts @@ -880,6 +880,14 @@ export function defineStore( id = idOrOptions.id } + // Warn developers about existing store ID in dev environments + if (__DEV__ && activePinia?._k.includes(id)) { + console.warn(`[🍍]: Stores should have unique identifiers. Found multiple stores with id "${id}". Rename one of them.`) + } + + // Push ID to keys registry + activePinia?._k.push(id) + function useStore(pinia?: Pinia | null, hot?: StoreGeneric): StoreGeneric { const currentInstance = getCurrentInstance() pinia =