react-query v4 공식문서 : Query Functions

👾·2022년 8월 4일
0

react-query

목록 보기
5/27
post-thumbnail

공식 문서 : https://tanstack.com/query/v4/docs/guides/query-functions

Query Functions

query function은 말 그대로 Promise를 반환하는 모든 함수일 수 있다. 반환되는 promise는 data를 resolve하거나 error를 throw한다.

다음은 모두 유효한 쿼리 함수 구성이다. :

useQuery(['todos'], fetchAllTodos)
useQuery(['todos', todoId], () => fetchTodoById(todoId))
useQuery(['todos', todoId], async () => {
  const data = await fetchTodoById(todoId)
  return data
})
useQuery(['todos', todoId], ({ queryKey }) => fetchTodoById(queryKey[1]))

Handling and Throwing Errors

React Query가 쿼리에 에러가 있다고 판단하려면 query function이 반드시 throw해야한다. query function에서 throw된 모든 에러는 쿼리의 error state에 유지된다.

const { error } = useQuery(['todos', todoId], async () => {
  if (somethingGoesWrong) {
    throw new Error('Oh no!')
  }

  return data
})

Usage with fetch and other clients that do not throw by default

axiosgraphql-request 같은 대부분의 유틸리티들은 실패한 HTTP 호출에 대해 자동으로 에러를 throw하지만, fetch와 같은 일부 유틸리티들은 기본적으로 에러를 throw하지 않는다. 만약 그렇다면, 당신은 스스로 이를 throw할 필요가 있다. 여기 널리 사용되는 fetch API를 이용하는 간단한 방법이 있다. :

useQuery(['todos', todoId], async () => {
  const response = await fetch('/todos/' + todoId)
  if (!response.ok) {
    throw new Error('Network response was not ok')
  }
  return response.json()
})

Query Function Variables

쿼리 키들은 fetching하는 데이터를 고유하게 식별하기 위한것 뿐만 아니라, QueryFunctionContext의 일부로 query function에 편리하게 전달된다. 항상 필요한것은 아니지만 필요한 경우 query function을 추출할 수 있다. :

function Todos({ status, page }) {
  const result = useQuery(['todos', { status, page }], fetchTodoList)
}

// Access the key, status and page variables in your query function!
function fetchTodoList({ queryKey }) {
  const [_key, { status, page }] = queryKey
  return new Promise()
}

QueryFunctionContext

QueryFunctionContext는 각 query function에 전달되는 객체이다. 구성요소는 다음과 같다 :

  • queryKey : QueryKey : 쿼리 키
  • pageParam : unknown | undefined
    • Infinite Query 전용
    • 현재 페이지를 fetch하는데 사용되는 페이지 파라미터
  • signal? : AbortSignal
    • react query에서 제공되는 AbortSignal 인스턴스
    • Query Cancellation에 사용될 수 있음
  • meta? : Record<string, unknown>
    • 쿼리에 대한 추가 정보로 채울 수 있는 옵션 필드

Using a Query Object instead of parameters

React Query API에서 [queryKey, queryFn, config] signature가 지원되는 곳이라면 어디든지 객체를 사용하여 동일한 설정을 표현할 수 있다.

import { useQuery } from '@tanstack/react-query'

useQuery({
  queryKey: ['todo', 7],
  queryFn: fetchTodo,
  ...config,
})

0개의 댓글