From 667b81dfd7888bbae562bbd02c3670d4c664a8e2 Mon Sep 17 00:00:00 2001 From: Pouya Mohammadkhani <31730646+BlackCrowxyz@users.noreply.github.com> Date: Fri, 17 Jun 2022 13:43:27 +0430 Subject: [PATCH] feat: warn when a getter conflicts with the state (#1356) Co-authored-by: Eduardo San Martin Morote --- packages/pinia/__tests__/store.spec.ts | 12 ++++++++++++ packages/pinia/src/store.ts | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/packages/pinia/__tests__/store.spec.ts b/packages/pinia/__tests__/store.spec.ts index cdab3deb..d5122d58 100644 --- a/packages/pinia/__tests__/store.spec.ts +++ b/packages/pinia/__tests__/store.spec.ts @@ -366,4 +366,16 @@ describe('Store', () => { useMyStore() expect(warnTextCheckPlainObject('poInit')).toHaveBeenWarnedTimes(0) }) + + it('warns when state name conflicts with getters name (with id as first argument)', () => { + const useStore = defineStore('main', { + state: () => ({ anyName: 0 }), + getters: { anyName: (state) => state.anyName }, + }) + useStore() + + expect( + `[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "anyName" in store "main".` + ).toHaveBeenWarnedTimes(1) + }) }) diff --git a/packages/pinia/src/store.ts b/packages/pinia/src/store.ts index 9987608a..d7156a0e 100644 --- a/packages/pinia/src/store.ts +++ b/packages/pinia/src/store.ts @@ -149,6 +149,12 @@ function createOptionsStore< localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => { + if (__DEV__ && name in localState) { + console.warn( + `[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".` + ) + } + computedGetters[name] = markRaw( computed(() => { setActivePinia(pinia) -- 2.47.3