query: Incorrect types for suspense

Describe the bug I have been playing around with v2 and v3 to experiment for a new project, and have noticed that the returned type for useQuery is incorrect with suspense.

I am beginning to think there should be an aliased function with different return types for suspense.

To Reproduce

  1. Write any code that uses useQuery
const { data } = useQuery<Todo[]>('todos', getTodos);
  1. Notice that you can’t use data in a typescript project without first checking if its undefined because the returned type is Todo[] | undefined

About this issue

  • Original URL
  • State: closed
  • Created 4 years ago
  • Reactions: 18
  • Comments: 17 (1 by maintainers)

Most upvoted comments

Are there any plans to add useSuspenseQuery?

yes

ah okay, got it. so what we would need to do, on type level, is return T rather than T | undefined if the option suspense was set to true?

The only way to make this work is to create separate suspense hooks as the suspense option can be set globally. But I guess the data could still be undefined if enabled is set to false for example.

Hello, Are there any plans to add useSuspenseQuery?

@predrag-codetribe If you need it now, you can use this @suspensive/react-query(https://tanstack.com/query/v4/docs/react/community/suspensive-react-query) first in v4.

I’d like to note that this is community resources.

If the code does not ever specify enabled: false for a specific query, shouldn’t the type exclude undefined?

there are still edge cases where data can still be undefined, e.g. if queryClient.cancelQueries is called while you are fetching data for the first time. It’s also very hard to do on type level. There is some motion going on for excluding undefined from type if initialData is specified here:

For suspense, we’d probably need a separate useSuspenseQuery hook to make it work…

Sorry to comment on an old issue, but was this solved somehow? If I set initialData in a useQuery I still get T | undefined, even though afaik it should only be T