TanStackT
TanStack3y ago
4 replies
sacred-rose

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()


But that seems awfully hacky, and considering im new to the lib I don't want to start doing something anti-pattern
Was this page helpful?