React Query Prefetching

gyujae·2022년 8월 30일
0
post-custom-banner

prefetch

  • adds data to cache

  • automatically stale (configurable)

  • show while re-fetching (as long as cache hasn't expired!)

  • Prefetching can be used for any anticipated data needs (not just pagination!)

https://tanstack.com/query/v4/docs/guides/prefetching

const [currentPage, setCurrentPage] = useState(0);
const [selectedPost, setSelectedPost] = useState(null);
const queryClient = useQueryClient();
// replace with useQuery
const { data, isLoading, isError, error } = useQuery(['posts', currentPage], () => fetchPosts(currentPage), {
    staleTime: 20000,
    keepPreviousData: true
  });;
  
useEffect(() => { 
  if (currentPage < maxPostPage) {
    const nextPage = currentPage + 1;
    queryClient.prefetchQuery(['posts', nextPage], () => fetchPosts(nextPage))
  }
},[currentPage, queryClient])

if (isLoading) {
  return <h3>Loading...</h3>
}
if (isError) {
  return (
    <>
      <h3>Oops,, Something went wrong..</h3>
      <p>{error.toString()}</p>
      </>
  )
}
post-custom-banner

0개의 댓글