본문 바로가기

programming/React

useQuery enable (false) 비활성화 일때 isLoading = true 인 이슈

useQuery 를 사용하면서 특정 조건에 따라서 query 를 실행/미실행 하려고 한다

  const { data, error, isLoading } = useQuery(
    ["test", "detail", id],
    () => getDetail({ id }),
	{enabled: !!id}
   )

 

 

id가 있을 때만 query 요청하기

조건 기준이 되는 값은 반드시 queryKey 에 포함이 되어있어야 enabled 가 작동된다

 

 

id 가 없어서 query 요청을 안하는 경우인데도 isLoading = true 로 설정되어, 로딩 스피너가 계속 돌았다.

 

이에 대한 해결책은

react-query v4에서 isInitialLoading이라는 새로운 인자를 반환해준다.

 

react-query 공식 문서에서 isInitialLoading 에 대한 설명을 보면, isFetching 과 isLoading 의 AND 연산 값이다

즉 실제로 fetching 하고 있는가 + loading 중인가 체크함

  • isInitialLoading: boolean
    • Is true whenever the first fetch for a query is in-flight
    • Is the same as isFetching && isLoading

 

 

관련 링크

https://github.com/TanStack/query/issues/3584

 

[Beta] Disabled query has `isLoading: true` property · Issue #3584 · TanStack/query

Describe the bug In react-query@beta version has strange behaviour. By default query that has enabled: false option has isLoading: true property (see code sandbox for details). In stable release re...

github.com

 

https://tanstack.com/query/v4/docs/react/reference/useQuery

 

useQuery | TanStack Query Docs

Does this replace [Redux, MobX, etc]?

tanstack.com