From 254eec764ecccd120ab9dbc31352d76ffd6ecfa3 Mon Sep 17 00:00:00 2001 From: babu-ch <42715882+babu-ch@users.noreply.github.com> Date: Thu, 17 Oct 2024 12:09:34 +0900 Subject: [PATCH] fix: reference the store directly in storeToRefs to ensure correct reactivity after HMR (#2795) --- packages/pinia/__tests__/storeToRefs.spec.ts | 20 ++++++++++++++++++++ packages/pinia/src/storeToRefs.ts | 6 +++--- 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/packages/pinia/__tests__/storeToRefs.spec.ts b/packages/pinia/__tests__/storeToRefs.spec.ts index d7e6a5f2f6..d1110e8c13 100644 --- a/packages/pinia/__tests__/storeToRefs.spec.ts +++ b/packages/pinia/__tests__/storeToRefs.spec.ts @@ -1,6 +1,7 @@ import { describe, beforeEach, it, expect } from 'vitest' import { computed, reactive, ref, ToRefs } from 'vue' import { createPinia, defineStore, setActivePinia, storeToRefs } from '../src' +import { set } from 'vue-demi' describe('storeToRefs', () => { beforeEach(() => { @@ -170,6 +171,25 @@ describe('storeToRefs', () => { expect(refs.n.value).toBe(2) }) + it('keep reactivity', () => { + const store = defineStore('a', () => { + const n = ref(0) + const double = computed(() => n.value * 2) + return { n, double } + })() + + const { double } = storeToRefs(store) + + // Assuming HMR operation + set( + store, + 'double', + computed(() => 1) + ) + + expect(double.value).toEqual(1) + }) + tds(() => { const store1 = defineStore('a', () => { const n = ref(0) diff --git a/packages/pinia/src/storeToRefs.ts b/packages/pinia/src/storeToRefs.ts index 9e5dab0e4b..3a1cec09f5 100644 --- a/packages/pinia/src/storeToRefs.ts +++ b/packages/pinia/src/storeToRefs.ts @@ -94,11 +94,11 @@ export function storeToRefs( // @ts-expect-error: toRefs include methods and others return toRefs(store) } else { - store = toRaw(store) + const rawStore = toRaw(store) const refs = {} as StoreToRefs - for (const key in store) { - const value = store[key] + for (const key in rawStore) { + const value = rawStore[key] if (isRef(value) || isReactive(value)) { // @ts-expect-error: the key is state or getter refs[key] =