T
TanStack4y ago
conscious-sapphire

If staleTime set my data isn't refetched even the queryKey array changes.

When offset state is changed my query isn't refetched
const { data, status } = useQuery<PaginatedData<never>>(
[url, offset],
(context) => {

return fetcher(getUrl(0));
},
{
initialData: initialData,
keepPreviousData: true,
refetchOnMount: false,
refetchOnWindowFocus: false,
staleTime:5000
}
);
const { data, status } = useQuery<PaginatedData<never>>(
[url, offset],
(context) => {

return fetcher(getUrl(0));
},
{
initialData: initialData,
keepPreviousData: true,
refetchOnMount: false,
refetchOnWindowFocus: false,
staleTime:5000
}
);
4 Replies
harsh-harlequin
harsh-harlequin4y ago
If you have initialData and staleTime set it won't be fetched until staleTime passes. It is working as intended. placeholderData has different behavior. Maybe it will be useful for you.
harsh-harlequin
harsh-harlequin4y ago
yeah, Mr. Mentor is right. By setting initialData, you're providing it for all cache keys. Maybe you only want to set it for the first offset or something like that? Or, you want placeholderData... I have a blog post on the differences: https://tkdodo.eu/blog/placeholder-and-initial-data-in-react-query
conscious-sapphire
conscious-sapphireOP4y ago
My data comes from getServerSideProps and it's valid. Even though it's not optimal, I choosed placeholderData. For loading state i used
isLoading={isFetching && !isPlaceholderData}
isLoading={isFetching && !isPlaceholderData}
Page refetches the first query but other functions works good.
harsh-harlequin
harsh-harlequin4y ago
the data is likely valid for the first key only. if the key changes, you don't want that data in the cache. So you need to write that logic in the initial data function

Did you find this page helpful?