Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: warn developers for duplicated store keys #1731

Open
wants to merge 2 commits into
base: v2
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 12 additions & 0 deletions packages/pinia/__tests__/store.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
})
1 change: 1 addition & 0 deletions packages/pinia/src/createPinia.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ export function createPinia(): Pinia {
_a: null,
_e: scope,
_s: new Map<string, StoreGeneric>(),
_k: [],
state,
})

Expand Down
8 changes: 8 additions & 0 deletions packages/pinia/src/rootStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,14 @@ export interface Pinia {
*/
_s: Map<string, StoreGeneric>

/**
* Registry of store ids defined in this pinia instance.
* This is used to check for duplicated keys.
*
* @internal
*/
_k: Array<string>

/**
* Added by `createTestingPinia()` to bypass `useStore(pinia)`.
*
Expand Down
8 changes: 8 additions & 0 deletions packages/pinia/src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down