T
TanStack2y ago
wise-white

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
export const useUsers = () => {
const query = useQuery({
queryKey: ['users'],
queryFn: () => getUsers,
// placeholderData], <--- putting it here doesn't change T | undefined
})
return {...query, users: query.data ?? placeholderData}
}

// consumer
// users: User[]
// data: User[] | undefined
const {users} = useUsers()
export const useUsers = () => {
const query = useQuery({
queryKey: ['users'],
queryFn: () => getUsers,
// placeholderData], <--- putting it here doesn't change T | undefined
})
return {...query, users: query.data ?? placeholderData}
}

// consumer
// users: User[]
// data: User[] | undefined
const {users} = useUsers()
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
rising-crimson2y ago
you could use useQuerySuspense and just deal with the happy path in your immediate code
like-gold
like-gold2y ago
initialData is your friend
wise-white
wise-whiteOP2y ago
That works perfectly, thank you!
No description
like-gold
like-gold2y 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:

Did you find this page helpful?