T
TanStack2y ago
like-gold

React Query fetches data even if staleTime is set to Infinity

Hello, hope everyone is doing great. First time I am using React Query, so excuse the noobiness. I am trying to understand React Query through this simple example (local server) where I check the Network tab to see if requests are made when data is fresh. Whenever I refresh the page, an HTTP request is fired, even if data is not stale (I am using React Query Devtools to check this)
export default function App() {
const { isPending, error, data } = useQuery({
queryKey: ['repoData'],
queryFn: () => fetch('http://localhost:8000/api/v1/getservices').then((res) => res.json()),
staleTime: Infinity
});

if (isPending) return 'Loading...';

if (error) return 'An error has occurred: ' + error.message;

return (
<ul>
{data.map((category) => (
<li>{category.category_name}</li>
))}
</ul>
);
}
export default function App() {
const { isPending, error, data } = useQuery({
queryKey: ['repoData'],
queryFn: () => fetch('http://localhost:8000/api/v1/getservices').then((res) => res.json()),
staleTime: Infinity
});

if (isPending) return 'Loading...';

if (error) return 'An error has occurred: ' + error.message;

return (
<ul>
{data.map((category) => (
<li>{category.category_name}</li>
))}
</ul>
);
}
6 Replies
ratty-blush
ratty-blush2y ago
If you refresh the whole page then yes of course your requests would be fetched again. If you want better persistence, there's some localStorage plugins you could use
like-gold
like-goldOP2y ago
isn't one of the points of React Query not to fetch data when it's fresh?
ratty-blush
ratty-blush2y ago
Not when you reload an entire page
ratty-blush
ratty-blush2y ago
persistQueryClient | TanStack Query Docs
This is set of utilities for interacting with "persisters" which save your queryClient for later use. Different persisters can be used to store your client and cache to many different storage layers. Build Persisters
ratty-blush
ratty-blush2y ago
Check some of those plugins
like-gold
like-goldOP2y ago
I see... so React Query as is will be more suitable for SPAs? because it's rare to have full page refreshes or am I confusing stuff? thanks for the clarification btw! I appreciate it

Did you find this page helpful?