T
TanStack14mo ago
wise-white

useQueries question

Hi gang, I'm looking for some guidance with UseQueries: I'm using useQueries to combine queries that I have already defined custom hooks for. It seems that I can get away with only specifying queryKey in the queries array of useQueries. The function seems to map the queryFn already defined for each queryKey. However the documentation for useQueries is a bit sparse so Im unsure if this is an acceptable pattern. Should I instead redefine the function for each entry in queries?
4 Replies
robust-apricot
robust-apricot14mo ago
useQueries is "the same" as calling useQuery multiple times; every call needs a queryFn unless you have a global one defined
wise-white
wise-whiteOP14mo ago
Based on the Default Query Function section of the documentation, it seems that this is supported. However I'm having a hard time understanding how I'm getting from A to B. For example, I have defined a few hooks that call useQuery throughout my code:
function useTodos() {
return useQuery({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetchHttpData('/todos');
return response;
},
});
}

function useProducts() {
return useQuery({
queryKey: ['products'],
queryFn: async () => {
const response = await fetchHttpData('/products');
return response;
},
});
}
function useTodos() {
return useQuery({
queryKey: ['todos'],
queryFn: async () => {
const response = await fetchHttpData('/todos');
return response;
},
});
}

function useProducts() {
return useQuery({
queryKey: ['products'],
queryFn: async () => {
const response = await fetchHttpData('/products');
return response;
},
});
}
Those work as expected when I need to use them individually. In a scenario where I need to fetch them in parallel, I'm doing this:
const combineFn = useCallback((results: UseQueryResult[]) => {
return {
data: results.map((result) => result.data),
pending: results.some((result) => result.isPending),
};
}, []);

const combined = useQueries({
queries: [
{ queryKey: ['todos'] },
{ queryKey: ['products'] },
],
combine: combineFn,
});
const combineFn = useCallback((results: UseQueryResult[]) => {
return {
data: results.map((result) => result.data),
pending: results.some((result) => result.isPending),
};
}, []);

const combined = useQueries({
queries: [
{ queryKey: ['todos'] },
{ queryKey: ['products'] },
],
combine: combineFn,
});
Does that look right? Seems that useQueries is aware of the queryFn associated with each queryKey. Thank you. I suppose my follow up question, based on what I'm seeing, would be: Is usage of useQuery implicitly defining a queryFn globally?
robust-apricot
robust-apricot14mo ago
no, it does not. what you are showing is not the same. with useQuery, you pass a queryFn, with useQueries, you don't if you have a defaultQueryFn defined in defaultOptions, that is okay. otherwise, it's not.
wise-white
wise-whiteOP14mo ago
Thank you for your help

Did you find this page helpful?