T
TanStack2y ago
wise-white

Is there a way to rerun only partial code of a query?

Hey I have a question about queries. I have a query which makes multiple get requests and then does a Promise.all to resolve all promises.
const useChangeTariff = (contractIds: string[]): UseQueryResult<ITariffChange[], void> => {
return useQuery({
queryKey: [queryKeys.CHANGE_TARIFF, [contractIds]],
queryFn: async () => {
if (!contractIds) {
return {};
}
const promises = [];
for (let i = 0; i < contractIds.length; i++) {
promises.push(getChangeTariff(contractIds[i]));
}
const results = await Promise.all(promises);

const filteredResults = results
.map((res, index) => ({ ...res?.data, contractId: contractIds[index] }))
.filter((data) => data && !('success' in data)) as unknown as ITariffChange[];
if (!filteredResults || !filteredResults.length) {
return null;
}
return filteredResults;
},
enabled: Boolean(contractIds)
});
};
const useChangeTariff = (contractIds: string[]): UseQueryResult<ITariffChange[], void> => {
return useQuery({
queryKey: [queryKeys.CHANGE_TARIFF, [contractIds]],
queryFn: async () => {
if (!contractIds) {
return {};
}
const promises = [];
for (let i = 0; i < contractIds.length; i++) {
promises.push(getChangeTariff(contractIds[i]));
}
const results = await Promise.all(promises);

const filteredResults = results
.map((res, index) => ({ ...res?.data, contractId: contractIds[index] }))
.filter((data) => data && !('success' in data)) as unknown as ITariffChange[];
if (!filteredResults || !filteredResults.length) {
return null;
}
return filteredResults;
},
enabled: Boolean(contractIds)
});
};
As you can see I then do some filter logic based on the result. I would like now to have something like a filter function which updates on query key or whatever, but leave the api calls in cache. basically something like
// useQuery Input
{
...
filters: {
myCustomFilter: (queryContext, args) => {
// queryContext would then contain the return value of my query function
// and args would be whatever I define
return myFiltered array or whaterver
}
}
}
// useQuery Input
{
...
filters: {
myCustomFilter: (queryContext, args) => {
// queryContext would then contain the return value of my query function
// and args would be whatever I define
return myFiltered array or whaterver
}
}
}
2 Replies
rival-black
rival-black2y ago
you're looking for the select option
rival-black
rival-black2y ago
Render Optimizations | TanStack Query Docs
React Query applies a couple of optimizations automatically to ensure that your components only re-render when they actually need to. This is done by the following means: structural sharing

Did you find this page helpful?