React Query 공부 (3) pagination 구현

JunSeok·2023년 1월 16일
0

react-query

목록 보기
4/11
post-thumbnail

앞서 배운 react-query로 간단하게 pagination을 구현해보았다.

구현방식

  1. useState로 현재 페이지 저장(currentPage)

  2. 유저가 Next page 또는 Previous page 버튼을 누르면 currentPage를 업데이트 해준다.

  3. 같은 query key를 가지지만 currentPage를 다르게 하여 다른 cache data를 받는다.

// Posts.tsx
import { useState } from "react";
import { useQuery } from 'react-query'

const fetchPosts = async (pageNum) => {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts?_limit=10&_page=${pageNum}`
  );
  return response.json();
}

export const Posts = () => {
	const [currentPage, setCurrentPage] = useState(1);
  
  	const { data, isError, error, isLoading } = useQuery(["posts", currentPage], () => fetchPosts(currentPage))
    
    return (
    	<div>
          <button disabled={currentPage <= 1} onClick={() => {
            setCurrentPage((previousValue) => previousValue-1)
          }}>
            Previous page
          </button>
          <span>Page {currentPage}</span>
          <button disabled={currentPage >= maxPostPage} onClick={() => {
            setCurrentPage((previousValue) => previousValue+1)
          }}>
            Next page
          </button>
     	</div>
    )
    
  
}
profile
최선을 다한다는 것은 할 수 있는 한 가장 핵심을 향한다는 것

0개의 댓글