data is possibly undefined
I'm guarding with
if (error) return .. and if (isLoading) return .. like in the docs, however it still says data might be undefined? Whats the way to deal with this in tanstakc query now?7 Replies
extended-salmonOP•3y ago
wise-white•3y ago
@KremBanan Hi, when You destructure useQuery object like this
const { isLoading, error, data } = useQuery(...); You actually lose connections between properties, so TS doesn't know how isLoading is connected to data
https://tkdodo.eu/blog/react-query-and-type-script#type-narrowingReact Query and TypeScript
Combine two of the most powerful tools for React Apps to produce great user experience, developer experience and type safety.
extended-salmonOP•3y ago
Thanks. So is the suggested solution to not destructure and TS will infer this correctly?
FWIW, I see in the docs they are destructuring and the files is marked as
tsx:
https://tanstack.com/query/latest/docs/react/overview#enough-talk-show-me-some-code-alreadywise-white•3y ago
Yeap, don't destructure the object and in most cases, it will infer correctly, except in some very rare, complex cases
I'd recommend You use TkDodo's blog as a guideline. He described almost every use case and issue that You might have along the way. I used it myself when I was learning react query.
extended-salmonOP•3y ago
thanks. how come the docs are showing something that will error tho?
on the introductory page, seems weird. as is there should be some better way.
I'm still getting the possible undefined.
wise-white•3y ago
https://discord.com/channels/719702312431386674/1075430726809432105/1075430726809432105
Take a look at this one, maybe You have the same issue that I do.
extended-salmonOP•3y ago
As far as I understood, what I'm experiencing is expected. https://tanstack.com/query/v4/docs/react/typescript
You have to explicitly type narrow with if (isSuccess) { data...} to not have data | undefined
however I expected that when guarding for error and loading first, it would be inferred that data is not undefined after that
@denis.monastyrskyi nevermind, I was checking
error instead of iserror
it works as expectted now with destructuring as well.