[Tanstack Query] Query Status와 Fetch Status

tacowasabii·2024년 7월 11일

Tanstack Query

목록 보기
1/5
post-thumbnail

리액트 쿼리에서 중요한 두 가지 상태 값인 query statusfetch status에 대해 알아보자. 이 두 상태 값은 각각 데이터의 유무와 쿼리 함수의 실행 상태를 나타낸다.

Query Status

query status실제로 데이터를 받아왔는지 여부를 나타내는 상태 값이다. 이는 useQuery 훅의 반환 값 중 status를 통해 확인할 수 있다. query status는 세 가지 상태 값을 가진다:

  • pending: 아직 데이터를 받아오지 못한 상태
  • success: 데이터를 성공적으로 받아온 상태
  • error: 데이터를 받아오는 중에 에러가 발생한 상태

이 상태 값들은 각각 isPending, isError, isSuccess와 매칭된다.

예제 코드

const { data, status, error } = useQuery('fetchPosts', getPosts);

console.log(status); // 첫 번째: 'pending', 두 번째: 'success' 또는 'error'

컴포넌트가 처음 마운트되고 useQuery가 실행되면 초기 상태는 pending이다. 이후 데이터가 성공적으로 로드되면 success 상태가 되고, 에러가 발생하면 error 상태가 된다.

Fetch Status

fetch status는 쿼리 함수(queryFn)가 현재 실행 중인지 여부를 나타낸다. 이는 useQuery 훅의 반환 값 중 fetchStatus를 통해 확인할 수 있다. fetch status는 세 가지 상태 값을 가진다:

  • fetching: 쿼리 함수가 실행 중인 상태
  • paused: 쿼리 함수가 실행을 시작했지만 네트워크가 오프라인이어서 중단된 상태
  • idle: 쿼리 함수가 실행 중이지 않은 상태

예제 코드

const { data, fetchStatus } = useQuery('fetchPosts', getPosts);

console.log(fetchStatus); // 'fetching', 'paused', 'idle'

쿼리 함수가 실행 중일 때는 fetching 상태, 네트워크가 오프라인일 때는 paused 상태, 쿼리 함수가 실행 중이지 않을 때는 idle 상태가 된다.

상태 전환 다이어그램

초기 컴포넌트 마운트 시:

  • query status: pending
  • fetch status: fetching

네트워크 오프라인 시:

  • fetch status: paused

데이터 성공적으로 받아온 경우:

  • query status: success
  • fetch status: idle

에러 발생 시:

  • query status: error
  • fetch status: idle

데이터 리패치 시:

  • fetch status: fetching

정리

query statusfetch status는 독립적인 상태 값으로, 다양한 조합 형태로 나타날 수 있다. 예를 들어, 이상적인 상황에서는 pending & fetching 상태에서 success & idle 상태로 전환되지만, 에러가 발생하는 경우 error & idle 상태가 될 수도 있다. 이를 이용한 다양한 상황에 따른 예외처리를 간편하게 할 수 있다.

profile
LG CNS 클라우드 엔지니어 / 웹 프론트엔드 개발자

0개의 댓글