Skip to content

Commit

Permalink
fix(query): always use placeholderData
Browse files Browse the repository at this point in the history
Fix #154
  • Loading branch information
posva committed Jan 13, 2025
1 parent e17bd5d commit 4c6a3f7
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 1 deletion.
39 changes: 39 additions & 0 deletions src/use-query.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -567,6 +567,45 @@ describe('useQuery', () => {
})
expect(cache.getQueryData(['id'])).toBe(42)
})

it('uses the placeholderData immediately after changing the key', async () => {
const key = ref(1)
const placeholderData = { data: 'ok' }
const { wrapper } = mountSimple({
key: () => [key.value],
query: async () => ({ data: 'done' }),
placeholderData,
})

await flushPromises()

key.value++
await nextTick()
expect(wrapper.vm.data).toBe(placeholderData)
await flushPromises()
expect(wrapper.vm.data).not.toBe(placeholderData)
key.value++
expect(wrapper.vm.data).toBe(placeholderData)
})

// NOTE: same as above but added for regression testing
// https://github.com/posva/pinia-colada/issues/154
it('uses the placeholderData even if the query is invalidated after after changing the key', async () => {
const key = ref(1)
const placeholderData = { data: 'ok' }
const { wrapper } = mountSimple({
key: () => ['common', key.value],
query: async () => ({ data: 'done' }),
placeholderData,
})
const queryCache = useQueryCache()

await flushPromises()

key.value++
queryCache.invalidateQueries({ key: ['common'] })
expect(wrapper.vm.data).toBe(placeholderData)
})
})

describe('refresh data', () => {
Expand Down
6 changes: 5 additions & 1 deletion src/use-query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,11 @@ export function useQuery<

if (toValue(enabled)) refresh()
},
{ immediate: true },
{
immediate: true,
// We need to set the placeholderData immediately to avoid an undefined value
flush: 'sync',
},
)

// avoid adding a watcher if enabled cannot change
Expand Down

0 comments on commit 4c6a3f7

Please sign in to comment.