React-Query

Guides&Concepts_(Dependent Qeuries & Background Fetching indicators )

ecoEarth 2023. 3. 21. 02:17

Dependent Qeuries

Dependent Qeuries는 Dependent Qeuries가 실행되기 이전 실행되는 queries에 의존하는 queries다.

이렇게 Dependent Qeuries를 만들어주려면 따로 어떤 특별한 기능을 이용하는 것이 아니라, enabled옵션으로 상황을 조성해주는 것이다.

아래 예시는 userId가 제대로 받아오기이전까지는 실행되지않게 enabled옵션으로 환경을 조성해준 예시이다.

*enabled옵션이 false값일 경우 자동적으로 useQuery함수는 실행되지 않는다.  userId가 정상적으로 받아진다면?. !!userId는 true, userId가 정상적으로 받아지지 않는다면?. !!userId는 false이다. 따라서 userId가 정상적으로 받아지는 경우에만 의존적으로 두번째 useQeury가 실행된다.

 

 // Get the user
 const { data: user } = useQuery(['user', email], getUserByEmail)
 
 const userId = user?.id
 
 // Then get the user's projects
 const { isIdle, data: projects } = useQuery(
   ['projects', userId],
   getProjectsByUser,
   {
     // The query will not execute until the userId exists
     enabled: !!userId,
   }
 )
 
 // isIdle will be `true` until `enabled` is true and the query begins to fetch.
 // It will then go to the `isLoading` stage and hopefully the `isSuccess` stage :)

Background Fetching Indicators

query가 뱉어주는 'loading' state만으로도 데이터를 받아오는 중일때의 상황을 표시해줄 수 있긴하다. 근데 background환경에서 

refetching중일때도 무언가 표시를 해주고싶다면, 'isFetching' state를 활용하면 된다.

 function Todos() {
   const { status, data: todos, error, isFetching } = useQuery(
     'todos',
     fetchTodos
   )
 
   return status === 'loading' ? (
     <span>Loading...</span>
   ) : status === 'error' ? (
     <span>Error: {error.message}</span>
   ) : (
     <>
       {isFetching ? <div>Refreshing...</div> : null}
 
       <div>
         {todos.map(todo => (
           <Todo todo={todo} />
         ))}
       </div>
     </>
   )
 }

 

Displaying Global Background Fetching Loading State

만약 어떠한 개별적인 컴포넌트단위로 로딩상태를 표시해주는 것이 아니라, 전역적으로 관찰해서 로딩상태가 일어날때마다 무언가를 하고싶다면 다음과 같이 useIsFetching hook을 이용하면된다.

 import { useIsFetching } from 'react-query'
 
 function GlobalLoadingIndicator() {
   const isFetching = useIsFetching()
 
   return isFetching ? (
     <div>Queries are fetching in the background...</div>
   ) : null
 }