Skip to content

Commit

Permalink
fix: reference the store directly in storeToRefs to ensure correct re…
Browse files Browse the repository at this point in the history
…activity after HMR (#2795)
  • Loading branch information
babu-ch authored Oct 17, 2024
1 parent e645fc1 commit 254eec7
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 3 deletions.
20 changes: 20 additions & 0 deletions packages/pinia/__tests__/storeToRefs.spec.ts
Original file line number Diff line number Diff line change
@@ -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(() => {
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 3 additions & 3 deletions packages/pinia/src/storeToRefs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,11 +94,11 @@ export function storeToRefs<SS extends StoreGeneric>(
// @ts-expect-error: toRefs include methods and others
return toRefs(store)
} else {
store = toRaw(store)
const rawStore = toRaw(store)

const refs = {} as StoreToRefs<SS>
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] =
Expand Down

0 comments on commit 254eec7

Please sign in to comment.