๐Ÿ‘€ Suspensive v2์—์„œ์˜ ๋ณ€๊ฒฝ์„ ํ™•์ธํ•˜์„ธ์š”. ๋”๋ณด๊ธฐ โ†’
๋ฌธ์„œ๋ณด๊ธฐ@suspensive/react-queryusePrefetchQuery

usePrefetchQuery

usePrefetchQuery๋Š” ์•„๋ฌด๊ฒƒ๋„ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š์œผ๋ฉฐ, useSuspenseQuery๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ๋ฅผ ๋ž˜ํ•‘ํ•˜๋Š” suspense boundary๊ฐ€ ๋ Œ๋” ๋˜๊ธฐ์ „์— prefetch๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ๋ฐ์— ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

import { usePrefetchQuery, useSuspenseQuery } from '@suspensive/react-query'
 
const PostPage = ({ postId }) => {
  usePrefetchQuery({
    queryKey: ['posts', postId],
    queryFn: () => getPost(postId),
  }) // suspense๊ฒฝ๊ณ„ ์ „์— prefetch๋ฅผ ๋ฐœ์ƒ ์‹œํ‚ค๋Š” ๋ฐ์— ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค
 
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <Post postId={postId} />
    </Suspense>
  )
}
 
export const Post = ({ postId }) => {
  const { data } = useSuspenseQuery({
    queryKey: ['posts', postId],
    queryFn: () => getPost(postId),
  })
 
  return <>...</>
}
import { Suspense } from '@suspensive/react'
import { usePrefetchQuery, useSuspenseQuery } from '@suspensive/react-query'
import { useState } from 'react'

export const Example = () => {
  const [postId, setPostId] = useState(1)
  usePrefetchQuery({
    queryKey: ['posts', postId],
    queryFn: () => getPost(postId),
  }) // suspense๊ฒฝ๊ณ„ ์ „์— prefetch๋ฅผ ๋ฐœ์ƒ ์‹œํ‚ค๋Š” ๋ฐ์— ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค

  return (
    <div>
      <button
        onClick={() => setPostId((prev) => prev - 1)}
        disabled={postId === 1}
      >
        Previous Post
      </button>
      <button
        onClick={() => setPostId((prev) => prev + 1)}
        disabled={postId === 100}
      >
        Next Post
      </button>
      <Suspense fallback={<div>Loading...</div>}>
        <Post postId={postId} />
      </Suspense>
    </div>
  )
}

const Post = ({ postId }: { postId: number }) => {
  const { data } = useSuspenseQuery({
    queryKey: ['posts', postId],
    queryFn: () => getPost(postId),
  })

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  )
}

const getPost = (postId: number) =>
  fetch(`https://jsonplaceholder.typicode.com/posts/${postId}`).then<{
    id: number
    title: string
    body: string
  }>((res) => res.json())