T
TanStack8mo ago
like-gold

How do you define your custom hook?

Title might be misleading because I know how to make a custom hook. What I wonder is if there is some better way to do it? What are yours "go to" custom hook implementation? How do you add more options to it as a argument?
5 Replies
like-gold
like-goldOP8mo ago
Here is my most basic example hook and problem I'm often facing:
export function useTodos(status?: waiting|inProgress|done|all){
return useQuery({
queryKey: ["todo","list",status],
queryFn: ()=>fetchTodos(status!),
enabled: !!status
})
}
export function useTodos(status?: waiting|inProgress|done|all){
return useQuery({
queryKey: ["todo","list",status],
queryFn: ()=>fetchTodos(status!),
enabled: !!status
})
}
But sometimes I must add additional arguments to the function, let's say onSuccess callback, I usually did it just by providing additional argument, because I couldn't make this solution work:
export function useTodos(status?: waiting|inProgress|done|all, options?: Omit<QueryOptions,'queryKey'|'queryFn'){
return useQuery({
queryKey: ["todo","list",status],
queryFn: ()=>fetchTodos(status!),
enabled: !!status,
...options
})
}
export function useTodos(status?: waiting|inProgress|done|all, options?: Omit<QueryOptions,'queryKey'|'queryFn'){
return useQuery({
queryKey: ["todo","list",status],
queryFn: ()=>fetchTodos(status!),
enabled: !!status,
...options
})
}
Because it was giving me type errors, I was loosing my return type etc.
optimistic-gold
optimistic-gold8mo ago
Look into queryOptions creator's instead Also onSuccess was removed in v5
like-gold
like-goldOP8mo ago
creator's? Sorry but I don't get it You mean generics?
optimistic-gold
optimistic-gold8mo ago
Query Options | TanStack Query React Docs
One of the best ways to share queryKey and queryFn between multiple places, yet keep them co-located to one another, is to use the queryOptions helper. At runtime, this helper just returns whatever yo...
optimistic-gold
optimistic-gold8mo ago
By creators I mean:
const creator = (id: string) => queryOptions({
queryKey: ["query", id]
queryFn: () => { ... }
})
const creator = (id: string) => queryOptions({
queryKey: ["query", id]
queryFn: () => { ... }
})
And you can spread more options into the result of creator later on.

Did you find this page helpful?