Skip to content

Commit

Permalink
fix(svelte-query): allow returning undefined in initialData function (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
lachlancollins authored Aug 2, 2024
1 parent 0f6a1d5 commit e092f06
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 10 deletions.
9 changes: 7 additions & 2 deletions packages/svelte-query/src/queryOptions.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
import type { DataTag, DefaultError, QueryKey } from '@tanstack/query-core'
import type {
DataTag,
DefaultError,
InitialDataFunction,
QueryKey,
} from '@tanstack/query-core'
import type { CreateQueryOptions } from './types.js'

export type UndefinedInitialDataOptions<
Expand All @@ -7,7 +12,7 @@ export type UndefinedInitialDataOptions<
TData = TQueryFnData,
TQueryKey extends QueryKey = QueryKey,
> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
initialData?: undefined
initialData?: undefined | InitialDataFunction<NonUndefinedGuard<TQueryFnData>>
}

type NonUndefinedGuard<T> = T extends undefined ? never : T
Expand Down
20 changes: 12 additions & 8 deletions packages/svelte-query/tests/createQuery/createQuery.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,24 @@ describe('createQuery', () => {
test('TData should be defined when passed through queryOptions', () => {
const options = queryOptions({
queryKey: ['key'],
queryFn: () => {
return {
wow: true,
}
},
initialData: {
wow: true,
},
queryFn: () => ({ wow: true }),
initialData: { wow: true },
})
const query = createQuery(options)

expectTypeOf(get(query).data).toEqualTypeOf<{ wow: boolean }>()
})

test('TData should always be defined when initialData is provided as a function which ALWAYS returns the data', () => {
const query = createQuery({
queryKey: ['key'],
queryFn: () => ({ wow: true }),
initialData: () => ({ wow: true }),
})

expectTypeOf(get(query).data).toEqualTypeOf<{ wow: boolean }>()
})

test('TData should have undefined in the union when initialData is NOT provided', () => {
const query = createQuery({
queryKey: ['key'],
Expand Down
19 changes: 19 additions & 0 deletions packages/svelte-query/tests/queryOptions/queryOptions.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -176,4 +176,23 @@ describe('queryOptions', () => {
QueriesObserver<Array<QueryObserverResult>>
>()
})

test('Should allow undefined response in initialData', () => {
return (id: string | null) =>
queryOptions({
queryKey: ['todo', id],
queryFn: () =>
Promise.resolve({
id: '1',
title: 'Do Laundry',
}),
initialData: () =>
!id
? undefined
: {
id,
title: 'Initial Data',
},
})
})
})

0 comments on commit e092f06

Please sign in to comment.