
공식 문서 : https://tanstack.com/query/v4/docs/guides/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]))
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
})
fetch and other clients that do not throw by defaultaxios나 graphql-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()
})
쿼리 키들은 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는 각 query function에 전달되는 객체이다. 구성요소는 다음과 같다 :
queryKey : QueryKey : 쿼리 키pageParam : unknown | undefinedsignal? : AbortSignalmeta? : Record<string, unknown> React Query API에서 [queryKey, queryFn, config] signature가 지원되는 곳이라면 어디든지 객체를 사용하여 동일한 설정을 표현할 수 있다.
import { useQuery } from '@tanstack/react-query'
useQuery({
queryKey: ['todo', 7],
queryFn: fetchTodo,
...config,
})