Skip to content

Commit

Permalink
docs: update usePrefetchQuery to avoid infinite refetching
Browse files Browse the repository at this point in the history
  • Loading branch information
iammminzzy committed May 18, 2024
1 parent 59eef10 commit e7ec7d5
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions docs/framework/react/guides/prefetching.md
Original file line number Diff line number Diff line change
Expand Up @@ -199,14 +199,18 @@ This starts fetching `'article-comments'` immediately and flattens the waterfall
If you want to prefetch together with Suspense, you will have to do things a bit differently. You can't use `useSuspenseQueries` to prefetch, since the prefetch would block the component from rendering. You also can not use `useQuery` for the prefetch, because that wouldn't start the prefetch until after suspenseful query had resolved. What you can do is add a small `usePrefetchQuery` function (we might add this to the library itself at a later point):

```tsx
const usePrefetchQuery = (...args) => {
const queryClient = useQueryClient()
function usePrefetchQuery(options) {
const queryClient = useQueryClient();

// This happens in render, but is safe to do because ensureQueryData
// only fetches if there is no data in the cache for this query. This
// means we know no observers are watching the data so the side effect
// is not observable, which is safe.
queryClient.ensureQueryData(...args)
if (!queryClient.getQueryState(options.queryKey)) {
queryClient.ensureQueryData(options).catch(() => {
// Avoid uncaught error
});
}
}
```

Expand Down

0 comments on commit e7ec7d5

Please sign in to comment.