query icon indicating copy to clipboard operation
query copied to clipboard

docs(react-query): fix prefetch with suspense example

Open qiushiyan opened this issue 1 year ago • 0 comments

In the docs, the current code example for prefetching with suspense queries is

function App() {
  usePrefetchQuery({
    queryKey: ['articles'],
    queryFn: (...args) => {
      return getArticles(...args)
    },
  })

  return (
    <Suspense fallback="Loading articles...">
      <Articles />
    </Suspense>
  )
}

function Articles() {
  const { data: articles } = useSuspenseQuery({
    queryKey: ['articles'],
    queryFn: (...args) => {
      return getArticles(...args)
    },
  })

  return articles.map((article) => (
    <div key={articleData.id}>
      <ArticleHeader article={article} />
      <ArticleBody article={article} />
    </div>
  ))
}

This might be a poor example:

  • the prefetch is followed directly by the suspense query, which does not bring much performance benefit,

  • all previous examples are dealing with the article item (primary data) and its comments (secondary data), the example is using a single query of the article list, which seems disconnected

  • I think what we want to demonstrate is prefetching the article comments while the article suspense component is pending, i.e.

function ArticleLayout({ id }) {
  usePrefetchQuery({
    queryKey: ['article-comments', id],
    queryFn: getArticleCommentsById,
  })

  return (
    <Suspense fallback="Loading article">
      <Article id={id} />
    </Suspense>
  )
}

function Article({ id }) {
  const { data: articleData, isPending } = useSuspenseQuery({
    queryKey: ['article', id],
    queryFn: getArticleById,
  })

  ...
}

qiushiyan avatar Oct 17 '24 21:10 qiushiyan