앞서 배운 react-query로 간단하게 pagination을 구현해보았다.
useState로 현재 페이지 저장(currentPage)
유저가 Next page 또는 Previous page 버튼을 누르면 currentPage를 업데이트 해준다.
같은 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>
)
}