T
TanStack10mo ago
vicious-gold

Stale data loading with ensureQueryData and useSuspenseQuery

in the docs there is this example about data loading
const postsQueryOptions = queryOptions({
queryKey: ['posts'],
queryFn: () => fetchPosts(),
})

export const Route = createFileRoute('/posts')({
// Use the `loader` option to ensure that the data is loaded
loader: () => queryClient.ensureQueryData(postsQueryOptions),
component: () => {
// Read the data from the cache and subscribe to updates
const {
data: { posts },
} = useSuspenseQuery(postsQueryOptions)

return (
<div>
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
</div>
)
},
})
const postsQueryOptions = queryOptions({
queryKey: ['posts'],
queryFn: () => fetchPosts(),
})

export const Route = createFileRoute('/posts')({
// Use the `loader` option to ensure that the data is loaded
loader: () => queryClient.ensureQueryData(postsQueryOptions),
component: () => {
// Read the data from the cache and subscribe to updates
const {
data: { posts },
} = useSuspenseQuery(postsQueryOptions)

return (
<div>
{posts.map((post) => (
<Post key={post.id} post={post} />
))}
</div>
)
},
})
I have a scenario where i go to this page, so the data is loaded, i go to a different page and call a mutation which invalidates postsQueryOptions . When i go back to the first page the data is not fetched again since ensureQueryData doesn't care about stale data. What is the preferred way of handling this? There is an parameter revalidateIfStale from ensureQueryData (Which i made the PR for) but wouldn't that throw an error on the useSuspenseQuery if that api for some reason throws an error?
2 Replies
deep-jade
deep-jade10mo ago
It should fetch again when useSuspenseQuery is remounted I think?
vicious-gold
vicious-goldOP10mo ago
A yeah sorry i totally messed up myself. I was fetching data with a param from the URL which was a string but the ID from the response is actually a number so the cache key didnt match up :/ Took me an hour to notice.

Did you find this page helpful?