데이터를 뿌릴때
- ux을 높이기
=> 다운로드 속도를 높이기 위해 - cost를 낮추기
페이지네이션의 주요 요소
- 페이지당 항목 수
- 총 데이터 개수
- 전체 페이지 수
ex ) 총 데이터 27개, 페이지당 항목수 5개, 전체 페이지수는 6개~!
상태를 가진다?
useState, useSelector가 선언되었는가
Array(총갯수).fill(채울값) = ✔️[...Array(총갯수)] // 같음, 오른쪽 코드가 더 간결
더보기 구현
useInfiniteQuery
- pages와 pageParams는 항상 짝을 이룸
- pages : 데이터
- pageParams : 페이지숫자
select 옵션 : 데이터 가공, select 결과값이 useQuery 데이터
lastPage : 서버에서 불러온 마지막 페이지
다음 페이지의 존재 여부를 미리 알 수 없을 때 (== 총 데이터 개수 또는 전체페이지수를 알 수 없을 때)
// 🤩 서버의 response에 totalCount 데이터가 포함되어 있던 경우
queryFn: async ({ pageParam }) => {
const response = await todoApi.get("/todos", {
params: { _page: pageParam, _limit: ITEMS_PER_PAGE },
});
return {
todos: response.data,
totalPages: Math.ceil(
response.headers["x-total-count"] / ITEMS_PER_PAGE,
),
};
},
// 🤔 서버의 response에 단순히 데이터만 들어있는 경우
queryFn: async ({ pageParam }) => {
const response = await todoApi.get("/todos", {
params: { _page: pageParam, _limit: ITEMS_PER_PAGE },
});
return response.data;
},
// lastPage 형식은 [ {...}, {...}, ... ] 라고 가정합니다.
getNextPageParam: (lastPage, allPages, lastPageParam) => {
const nextPage = lastPageParam + 1;
return lastPage.length === ITEMS_PER_PAGE ? nextPage : undefined;
},
// 4개씩 불러오기로 했는데 3개 불러왔으면 다음 페이지가 없다는 뜻
// 4개씩 불러오기로 했는데 4개 불러왔으면 다음 페이지는 있을 수도 있고 없을 수도 있다.
// 예를들어 총 데이터: 7개 , 4개씩 불러오기 , 1페이지: 4개, 2페이지: 3개 (다음 페이지 없음)
무한스크롤 구현
react-intersection-observer
- React에서 특정 요소가 화면에 보이는지 감지할 수 있는 라이브러리
- useInView
- threshold 옵션
- 1이면 요소가 100% 화면에 보여야 inView 상태로 인식
- 0이면 일부라도 보일 때 인식
https://www.npmjs.com/package/react-intersection-observer
react-intersection-observer
Monitor if a component is inside the viewport, using IntersectionObserver API. Latest version: 9.13.1, last published: 3 months ago. Start using react-intersection-observer in your project by running `npm i react-intersection-observer`. There are 1165 othe
www.npmjs.com
'개발 일기' 카테고리의 다른 글
2024-12-09(타입스크립트) (1) | 2024.12.09 |
---|---|
2024-12-06(optimistic update) (0) | 2024.12.06 |
2024-11-29(tanstack query) (0) | 2024.11.29 |
2024-11-27(상태관리,zustand) (0) | 2024.11.27 |
2024-11-25(rest api , axios, tanstack query) (1) | 2024.11.25 |