Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

queryOptions should to pass initialData with a callback that is potentially returning undefined #7341

Closed
ShacharHarshuv opened this issue Apr 26, 2024 · 9 comments · Fixed by #7351

Comments

@ShacharHarshuv
Copy link
Contributor

Describe the bug

In angular-query
When using queryOptions '@tanstack/angular-query-experimental' and passing an initial value function, typescript will not allow that typescript to return undefined. The following code will not compile:

interface Todo {
  id: string;
  title: string;
}

export const todoQueryOption = (id: string | null) =>
  queryOptions({
    queryKey: ['todo', id],
    queryFn: () =>
      Promise.resolve({
        id: '1',
        title: 'Do Laundry',
      }),
    initialData: (): Todo | undefined => undefined,
  });

This should be allowed because I might want to check if I have this particular "todo" item in the cache, and if I don't, I would want angular query to request that item. Since this is conditional, I have to put it in a function that might either have a todo or not (in the example I set it to undefined just for the example).

I believe this has to do with this type definition:

export type DefinedInitialDataOptions<
  TQueryFnData = unknown,
  TError = DefaultError,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
  initialData:
    | NonUndefinedGuard<TQueryFnData>
    | (() => NonUndefinedGuard<TQueryFnData>)
}

Which should be changed to:

export type DefinedInitialDataOptions<
  TQueryFnData = unknown,
  TError = DefaultError,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
> = CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
  initialData:
    | NonUndefinedGuard<TQueryFnData>
    | (InitialDataFunction<TQueryFnData>)
}

Your minimal, reproducible example

https://stackblitz.com/edit/stackblitz-starters-jdj53x?file=src%2Fmain.ts

Steps to reproduce

  1. Write this code in angular query:
interface Todo {
  id: string;
  title: string;
}

export const todoQueryOption = (id: string | null) =>
  queryOptions({
    queryKey: ['todo', id],
    queryFn: () =>
      Promise.resolve({
        id: '1',
        title: 'Do Laundry',
      }),
    initialData: (): Todo | undefined => undefined,
  });
  1. It wouldn't compile.

Expected behavior

The code should compile

How often does this bug happen?

Every time

Screenshots or Videos

No response

Platform

  • OS: Windows
  • Runtime: Node 20.11.0
  • (No browser is used to reproduce this bug)

Tanstack Query adapter

angular-query

TanStack Query version

5.32.0

TypeScript version

5.3.0

Additional context

No response

@ShacharHarshuv
Copy link
Contributor Author

Opened a PR that fixes this: #7351

@arnoud-dv
Copy link
Collaborator

Hi @TkDodo I'm not sure about this one. Code is identical to React adapter and I don't think initialData is supposed to be able to undefined?

@ShacharHarshuv
Copy link
Contributor Author

ShacharHarshuv commented Apr 29, 2024

The problematic types are defined in angular-query-experimental.

If an undefined return type is not supported than I'm not sure how the common use case will work. This example (from the docs) currently wouldn't work:

result = injectQuery(() => ({
  queryKey: ['todo', this.todoId()],
  queryFn: () => fetch('/todos'),
  initialData: () => {
    // Use a todo from the 'todos' query as the initial data for this todo query
    return this.queryClient
      .getQueryData(['todos'])
      ?.find((d) => d.id === this.todoId())
  },
}))

Also, this works in react-query:

const x = useQuery({
  initialData: () => undefined,
})

@TkDodo
Copy link
Collaborator

TkDodo commented Apr 29, 2024

it should work, but it also doesn't work in react query:

https://www.typescriptlang.org/play/?#code/JYWwDg9gTgLgBAbzgRwK4FMoE8DyYbAQB2AznAL5wBmUEIcA5AAIwCGpbAxgNYD0U6VpxgBaNJiwMAUFOBEYmKkPRwAKhAAmERFLhxgGgFxwSMKHIDmAbl1wCMADbpjp80WtTyM9AA9IsOE5iUztNCABFDGw8AmI4AF44AAoDFzNLOAAfOCJUBwcASgSAPltxaPxCUiSEWz1yrABpdCxjAG0GGDCGABp9DQBdHrqUKKwAMSJjJKL40r0FuAAFWhBgEnQAOgESCAcAN3QakcXUxgBGXpOF+ydjBgARbQAZVlQiDWwrxb1yAuHTkRgARWA4Hqw2NMCsZ1FosnB3hp0FQ5OgNCUER9kaiNACKAUrEA

I don't think your proposed solution is right though. I think we should rather extend UndefinedInitialDataOptions to be:

export type UndefinedInitialDataOptions<
  TQueryFnData = unknown,
  TError = DefaultError,
  TData = TQueryFnData,
  TQueryKey extends QueryKey = QueryKey,
> = UseQueryOptions<TQueryFnData, TError, TData, TQueryKey> & {
-  initialData?: undefined
-  initialData?: undefined | () => undefined
}

thoughts ?

@TkDodo
Copy link
Collaborator

TkDodo commented Apr 29, 2024

@TkDodo
Copy link
Collaborator

TkDodo commented Apr 29, 2024

okay interestingly, we have test that cover this case already, and they don't fail:

it('TData should have undefined in the union when initialData is provided as a function which can return undefined', () => {
const { data } = useQuery({
queryKey: ['key'],
queryFn: () => {
return {
wow: true,
}
},
initialData: () => undefined as { wow: boolean } | undefined,
})
expectTypeOf(data).toEqualTypeOf<{ wow: boolean } | undefined>()
})

🤔

@ShacharHarshuv
Copy link
Contributor Author

I don't think your proposed solution is right though. I think we should rather extend UndefinedInitialDataOptions

When looking at the types more closely I believe you are correct.

According to my understanding the idea is that UndefinedInitialDataOptions will return query result where data is possibly undefined, while DefinedInitialDataOptions returns query result where the data is required, so the consumer wouldn't need to handle the optional undefined value. According to that logic the option of () => T | undefined can result in a query that is possibly undefined, so it should be in the UndefinedInitlaDataOptions (Even though it's confusing, because the initialData is technically "defined").

I'll fix the PR accordingly.

@ShacharHarshuv
Copy link
Contributor Author

ShacharHarshuv commented Apr 29, 2024

okay interestingly, we have test that cover this case already, and they don't fail:

It doesn't fail because you use useQuery directly. The bug (both in angular and react) reproduces when you use queryOptions

@ShacharHarshuv
Copy link
Contributor Author

I fixed the PR per feedback: #7351

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
3 participants