Return the QueryKey from useQuery
#6752
-
Generally we defining one hook that creates the query, and then reusing it all over our codebase export const useSomeThing = (someArg,Arg2):QueryResult => {
return useQuery(["getSomeThing", someArg,Arg2] , ()=> "barf")
} We have a couple of components that accept a query key so they can monitor specific queries (a refetching indicator for example) It would be nice if |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
I'd recommend the
you can then pass this to Returning the values from |
Beta Was this translation helpful? Give feedback.
-
@TkDodo would you be willing to reconsider this request? I have a reusable query hook that determines the My current workaround is to use a custom import { type QueryKey, useQuery, type UseQueryResult } from '@tanstack/react-query';
export type UseQueryResultWithKey<TData = unknown, TError = unknown> = UseQueryResult<TData, TError> & {
queryKey: QueryKey;
};
export function useExampleQuery(identifiers: { id1?: string; id2?: string }): UseQueryResultWithKey<unknown, unknown> {
const queryKey = ['example', identifiers];
const query = useQuery({
queryKey: queryKey,
queryFn: () => loadFunction(identifiers)
});
return { ...query, queryKey };
} |
Beta Was this translation helpful? Give feedback.
I'd recommend the
queryOptions
function to abstract those away, and export it as a re-usable object:you can then pass this to
useQuery
as well as to other functions likeinvalidateQueries
or evenuseQueries
.Returning the values from
useQuery
doesn't make much sense because you can only then pass it down to components below that query, which doesn't cover cases where you need it in a sibling component. Calling the hook just to get the queryKey is also suboptimal, because it creates another subscriber. What you likely want is to abstract away the options.