data: T | undefined best practices
Heyo, I'm new to react-query. One stumbling block i'm running into is the best way to deal with data being T | undefined
I'm trying to make custom hooks that wrap useQuery (ex: useUsers()) and I'd like to reuse the hook in multiple parts of my app. The problem is dealing with undefined. my research has shown I can avoid object destructuring (ex const query = useQuery(...) ) and do if (query.isLoading) / if (query.error) and that'll gurantee data is defined.
But is it really normal practice to have to deal isLoading & error in -every- component that wants that data? I find that adds a lot of boilerplate to components who I'd hope would not have to worry about it. Sort've like how in Redux if I did const users = useSelector(selectUsers) I can count on Users being a User[]
The only solution I can think of is doing something like
But that seems awfully hacky, and considering im new to the lib I don't want to start doing something anti-pattern
4 Replies
rising-crimson•2y ago
you could use useQuerySuspense and just deal with the happy path in your immediate code
like-gold•2y ago
initialData
is your friendwise-whiteOP•2y ago
That works perfectly, thank you!

like-gold•2y ago
Initial Query Data | TanStack Query Docs
There are many ways to supply initial data for a query to the cache before you need it:
Declaratively: