T
TanStack4y ago
adverse-sapphire

Which Query to stale?

I have 2 hooks. 1 fetches the employers, the other manipulates the data. All I care about is that the data is fetched on mount. No other fetches are required. Do I set the hook that manipulates the data with the stale time (useFetchEmployersQuery) as that is the hook that I am using in my component and mapping through the data returned.
export const useFetchEmployers = () => {
return useQuery([employers.fetchEmployers],
async () => {
const { data } = await axios({
url: foo,
method: "get"
});
return data;
}
);
};

export const useFetchEmployersQuery = () => {
const platformEmployerTypes = [1, 3];

return useQuery([employers.fetchEmployers],
async () => {
const { data } = await axios({
url: foo,
method: "get"
});
return data;
},
{
select: (data) => data.filter((item) => platformEmployerTypes.includes(item.type))
},
{
staleTime: Infinity,
cacheTime: Infinity
}
);
};
export const useFetchEmployers = () => {
return useQuery([employers.fetchEmployers],
async () => {
const { data } = await axios({
url: foo,
method: "get"
});
return data;
}
);
};

export const useFetchEmployersQuery = () => {
const platformEmployerTypes = [1, 3];

return useQuery([employers.fetchEmployers],
async () => {
const { data } = await axios({
url: foo,
method: "get"
});
return data;
},
{
select: (data) => data.filter((item) => platformEmployerTypes.includes(item.type))
},
{
staleTime: Infinity,
cacheTime: Infinity
}
);
};
3 Replies
other-emerald
other-emerald4y ago
Hi you could set a global default staleTime to Infinity for this query. queryClient.setQueryDefaults([employers.fetchEmployers], {staleTime: Infinity, cacheTime: Infinity}) No need to bother anymore about which component creates the query
adverse-sapphire
adverse-sapphireOP4y ago
Ok cool! And where do setQueryDefaults usually live? In a utils file? But thinking about it, wouldn't useFetchEmployers then have the same global defaults as it uses the same key? [employers.fetchEmployers]
other-emerald
other-emerald4y ago
Yep, your 2 components use the same query so they share the same data set. Except that useFetchEmployersQuery uses a select so it listens to only a subset of the data
Ok cool! And where do setQueryDefaults usually live?
It depends but could be done directly when creating the queryClient

Did you find this page helpful?