TanStackT
TanStack14mo ago
2 replies
slow-yellow

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>
    )
  },
})

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?
Was this page helpful?