-
I've been experimenting with React Query's caching mechanisms but haven't found a straightforward way to implement this dynamic caching strategy based on the current time. Most examples or documentation I've found discuss setting a fixed cache time (e.g., using the staleTime option), but nothing that adjusts based on a function or the current time. Here's a pseudo-code example of what I'm trying to achieve, inspired by a function I've used outside of React Query context: export const shouldFetch = async <T>(storageKey: string): Promise<FetchResult<T>> => {
const cachedDataString = await AsyncStorage.getItem(storageKey);
if (cachedDataString) {
const { data, timestamp }: CachedData<T> = JSON.parse(cachedDataString);
const now = moment();
const timeToCompare = moment(timestamp);
return now.isSame(timeToCompare, 'hour') ? {
result: data,
refractor: false
} : {
result: undefined,
refractor: true
};
}
return {
result: undefined,
refractor: true
};
}; This function checks if the current hour is the same as the hour when the data was last fetched. If it is, it uses the cached data; otherwise, it indicates that a refetch is necessary. I'm trying to find the best way to integrate this logic with React Query. Would anyone have suggestions or examples on how to dynamically set the cache expiration or refetching criteria based on the current time or a similar function? Any guidance or pointers to resources that could help me implement this functionality would be greatly appreciated. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
Beta Was this translation helpful? Give feedback.
yes, that's pretty much what I said. It's not supported.
put staleTime and gcTime values in react state and update that state when you get a response