React Query - Pagenation

Code_Alpacat·2022년 10월 20일
0

1. Pagination

  • 데이터를 페이지마다 동적으로 가져와보자.

어떻게 요청 한 번에 하나씩 캐싱하지?

  • 다음의 예시를 보자.
async function fetchPosts(pageId) {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts?_limit=10&_page=${pageId}`
  );
  return response.json();
}

const { data, isLoading, isError } = useQuery(["posts"], () => fetchPosts(currentPage));
  • 위와 같이 데이터를 불러와서 적용하면 페이지를 넘길 때, 잘 받아와질까?

정답은 No.

  • React Query는 기본적으로 쿼리키 posts에 캐싱하도록 선언되어있다.
  • 즉, 페이지를 아무리 넘겨도 캐싱된 데이터는 같은 쿼리 키를 공유하므로 바뀌지 않는다.
  • 그러므로, 아래와 같이 리스트에 페이지마다 다른 쿼리 키에 캐싱되도록 해줘야한다.
async function fetchPosts(pageId) {
  const response = await fetch(
    `https://jsonplaceholder.typicode.com/posts?_limit=10&_page=${pageId}`
  );
  return response.json();
}

const { data, isLoading, isError } = useQuery(["posts", PAGE_ID], () => fetchPosts(currentPage));
  • 이제 제대로 작동하는 것을 볼 수 있다.

위의 useQuery는 이제 PAGE_ID에 의존성을 갖게 되었고, PAGE_ID가 바뀌면 새로 요청을 보내 해당 페이지를 출력해준다.

profile
In the future, I'm never gonna regret, cuz I've been trying my best for every single moment.

0개의 댓글

관련 채용 정보