Skip to content

Commit cac8263

Browse files
JSap0914posva
andauthored
feat: gracefully skip nullish values in storeToRefs (#3134)
Co-authored-by: Eduardo San Martin Morote <posva@users.noreply.github.com>
1 parent ec9b1eb commit cac8263

2 files changed

Lines changed: 18 additions & 1 deletion

File tree

‎packages/pinia/__tests__/storeToRefs.spec.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -200,6 +200,23 @@ describe('storeToRefs', () => {
200200
expect(spy).toHaveBeenCalledTimes(0)
201201
})
202202

203+
it('does not crash when setup store returns null non-ref value', () => {
204+
// A setup store may return a plain (non-ref) null value for optional state.
205+
// storeToRefs must skip those gracefully instead of throwing
206+
// TypeError: Cannot read properties of null (reading 'effect').
207+
const useStore = defineStore('null-val', () => {
208+
return {
209+
nullableItem: null as null | { id: number },
210+
text: ref('hello'),
211+
}
212+
})
213+
214+
const store = useStore()
215+
expect(() => storeToRefs(store)).not.toThrow()
216+
const { text } = storeToRefs(store)
217+
expect(text.value).toBe('hello')
218+
})
219+
203220
tds(() => {
204221
const store1 = defineStore('a', () => {
205222
const n = ref(0)

‎packages/pinia/src/storeToRefs.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ export function storeToRefs<SS extends StoreGeneric>(
9494
const value = rawStore[key]
9595
// There is no native method to check for a computed
9696
// https://github.com/vuejs/core/pull/4165
97-
if (value.effect) {
97+
if (value?.effect) {
9898
// @ts-expect-error: too hard to type correctly
9999
refs[key] =
100100
// ...

0 commit comments

Comments
 (0)