Notice
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 | 29 |
30 | 31 |
Tags
- 더블엔씨
- JS변수
- react-query v5
- 사내 이슈
- node.js
- MSW
- SSR
- 기술 낙서장
- 기술낙서장
- React
- Next.js
- 결제페이지
- react-query
- javascript
- ClientSide
- no router instance found
- SW캡스톤디자인
- 사내 오류 대응
- TypeScript
- react-query&Next.js
- state 관리
- React.JS
- react-query 도입후기
- state 사용하기
- 리액트
- 사내 오류 해결
- router instance
- 캡스톤디자인 후기
- 일상 생각
- nextjs
Archives
- Today
- Total
코딩을 잘하고 싶은 코린이 동토니
react-query fetch status에 관한 고찰 본문
1. data 캐싱 여부에 따른 initial status
- cached = true
- status === 'success'
- cached = false
- status === 'loading'
2. loading status
- 캐싱된 데이터가 없다면 항상 true
- 데이터를 호출 하고 나서야 false로 변경 (호출 이후 status = loading => 'success' | 'error')
- react-query에서의 loading의 의미는 데이터를 불러오는 중이 아닌 아직 데이터가 없는 상태
3. fetchStatus
- 기본 값 'idle' (쿼리가 아무런 동작도 하지 않는 상태)
- query 실행시 'fetching' 으로 상태 변경
4. enabled의 고찰
- useQuery 혹은 useQueries 옵션으로 enabled 사용시 아직 데이터가 없는 상태이므로 isLoading은 항상 true
- react-query v3에서는 isFetching && isLoading을 통해 enabled옵션에 따른 실행여부 판단 필요
- v4에 새롭게 생긴 isInitalLoading (isFetching && isLoading)을 통해 판단
공식문서 설명 Lazy queries will be in status: 'loading' right from the start because loading means that there is no data yet. This is technically true, however, since we are not currently fetching any data (as the query is not enabled), it also means you likely cannot use this flag to show a loading spinner.
If you are using disabled or lazy queries, you can use the isInitialLoading flag instead. It's a derived flag that is computed from: **isLoading && isFetching
so it will only be true if the query is currently fetching for the first time.
ex).
const queryResults = useQueries({
queries: [
{
queryKey: bannerKey.home,
queryFn: fetchHomeBanners,
enabled: shouldFetch,
},
{ queryKey: categoryKey.category1s, queryFn: fetchCategory1s },
{
queryKey: itemKey.recommendedItems(global.token),
queryFn: fetchRecommendedItems,
enabled: shouldFetch,
},
{
queryKey: categoryKey.top10Brands,
queryFn: fetchTop10Brands,
enabled: shouldFetch,
},
{
queryKey: eventCurationKey.latest,
queryFn: fetchLatestEventCuration,
enabled: shouldFetch,
},
{
queryKey: caseCurationKey.themes(global.token),
queryFn: fetchCaseCurationThemes,
enabled: shouldFetch,
},
{
queryKey: itemKey.newItems,
queryFn: fetchNewItems,
enabled: shouldFetch,
},
{
queryKey: itemKey.soonItems(global.token),
queryFn: fetchSoonItems,
enabled: shouldFetch,
},
{
queryKey: serviceSettingsKey.sellV2Config,
queryFn: fetchSellV2Config,
enabled: shouldFetch,
},
{
queryKey: sellerUsersKey.sellStatus(global.token),
queryFn: fetchSellStatus,
enabled: shouldFetch && Boolean(global.token),
},
],
})
Status 1. queryResult.map((result)=>result.isLoading)
1. [T,T,T,T,T,T,T,T,T] 초기 진입시
2. [F,F,F,F,F,F,F,F,T] 데이터 패치 이후
Status 2. queryResult.map((result)=>result.fetchStatus)
1. [fetching,fetching,fetching,fetching,fetching,fetching,fetching,fetching,idle]
초기 진입시
2. [idle,idle,idle,idle,idle,idle,idle,idle,idle] : 데이터 패치 이후
Status 3. queryResult.map((result)=>result.isInitialLoading)
1. [true,true,true,true,true,true,true,true,false] : 초기 진입시
2. [false,false,false,false,false,false,false,false,false] : 데이터 패치 이후
실제 적용 사례
내부 앱 fetchStatus에 따른 오류 해결을 위해 적용
useLayoutEffect(() => {
const isAllFetched = queryResults.every(
(queryResult) => !queryResult.isFetching,
)
const isAllError = queryResults.every(
(queriesResult) => queriesResult.isError,
)
const isAllLoaded = queryResults.every(
(queryResult) => !queryResult.isLoading,
)
if (isAllFetched) {
if (isAllError) {
handleNetworkError()
} else if (isAllLoaded) {
getPosthogEventMeta()
}
}
}, [queryResults, getPosthogEventMeta])
isLoading으로 체크하여 모든 데이터가 false여야 loaded로 판단하지만
마지막 쿼리의 경우 global.token이
enabled 옵션으로 들어가 있어 하나의 쿼리가 true로 되어있음 => 상태변화 X
const isAllLoaded = queryResults.every(
(queryResult) => !queryResult.isLoading,
)
해당 부분을 isInitialLoading으로 바꿀경우
마지막 쿼리는 항상 false이고 현재 시점에서 실행가능한 쿼리들은 true=> false로 상태가 변하기 때문에
실행가능한 쿼리들이 전부 실행되고 모든 status가 false로 변경되어 정상적인 loaded 판단 가능
이후 token값이 null => something일 경우 추가적으로 data fetch 진행
etc. useQueries의 재밌는 사실
- useQueries promise all로 구현되어 병렬처리가 진행 => 하나의 쿼리가 error 발생시 이후 진행되어야 하는 쿼리가 전부 error로 발생
- useQueries 사용시 하나의 쿼리만 에러가 발생되고 나머지는 정상 동작 시키려면 suspense 옵션 사용 => react 18 suspense 옵션을 통해 하나의 query가 에러 발생될 경우 해당 쿼리만 suspense 처리가 되도록 설정 가능
'Web > JavaScript' 카테고리의 다른 글
React-Query V5 변경점 정리 (0) | 2024.09.02 |
---|---|
JS 변수 (0) | 2022.01.05 |
Arrow function 과 일반 function 의 this (0) | 2021.09.30 |