Queries Functions
Query Function은 말그대로 promise를 리턴해주는 메서드이다. 그 promise는 데이터를 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]))
Handing and Throwing Errors
React Query는 query가 에러가 난다면 Query Function은 반드시 throw해야한다. Query Function에 의해 던져진 에러는 쿼리의error state에 의존된다. 이때 error state란 useQuery와 같이 Query Function이 return하는 값들중 하나이다.
아래 error가 구조분해할당된 부분을 참고해보자.
const { data, error } = useQuery('todos', async () => {
const response = await fetch('/todos')
if (error) {
throw new Error('Failed to fetch todos')
}
return response.json()
})
Usage with fetch and other clients that do not throw by default
axios나 graphql-request같은 유틸리티들은 대부분 HTTP calls에 실패하면 자동적으로 에러를 던진다. 근데 fetch같은 애들은
기본적으로 에러를 안던져줘서 직접 작성을 해줘야한다. 아래는 fetch를 사용할경우 에러를 던져주는 예시이다.
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
Query keys는 단지 데이터를 가져오는데 사용될 뿐 아니라, 쿼리함수에 편리하게 전달될 수 있다. 또 항상 필요한 것은 아니지만 필요한 경우 쿼리함수를 바깥으로 뺄 수 있도록 해준다. 아래는 쿼리함수를 바깥으로 뺀 예시이다.
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()
}
Using a Query Object instead of parameters
[queryKey, queryFn, config]와 같은 구성은 위에서 작성한 예시들 뿐 아니라, 객체로도 작성이 가능하다.
아래는 [queryKey, queryFn, config]의 구조를 객체로 작성한 예시이다.
import { useQuery } from 'react-query'
useQuery({
queryKey: ['todo', 7],
queryFn: fetchTodo,
...config,
})
Parallel Queries
Parallel queries는 말그대로 동시성을 위해 동시에 실행되는 queries를 의미한다.
Manual Parallel Queries
다음은 간단한 Parallel queries의 예시이다.
function App () {
// The following queries will execute in parallel
const usersQuery = useQuery('users', fetchUsers)
const teamsQuery = useQuery('teams', fetchTeams)
const projectsQuery = useQuery('projects', fetchProjects)
...
}
Dynamic Parallel Queries with useQueries
렌더가 계속되면서 실행하기를 원하는 쿼리의 숫자가 바뀔때에는 훅의 규칙을 위반하니까 useQueries 훅을 사용하라고 한다.
사실 어떤 훅의 규칙을 위반하는지는 잘 모르겠지만, suspense모드에서는 useQueries를 사용해야한다는것만 알고 넘어가자.
suspense 모드에서 useQueries를 사용해야 하는 이유는 useQuery를 병렬로 처리하여 사용하고 있을 때 만약 하나의 useQuery가 정상적으로 동작되지 않을 경우 그 이후에 실행될 useQuery에 영향을 미치며 결과적으로 올바른 화면이 보이지 않기 때문입니다.
https://react-query-v3.tanstack.com/guides/suspense (리액트 쿼리의 suspense mode문서부분)
useQueries사용예시는 다음과 같다.
function App({ users }) {
const userQueries = useQueries(
users.map(user => {
return {
queryKey: ['user', user.id],
queryFn: () => fetchUserById(user.id),
}
})
)
}
'React-Query' 카테고리의 다른 글
Guides&Concepts_(Window Focus Refetching & Disabling/Pausing Queries) (0) | 2023.03.21 |
---|---|
Guides&Concepts_(Dependent Qeuries & Background Fetching indicators ) (0) | 2023.03.21 |
Guides&Concepts_(Queries & Qeury Keys) (0) | 2023.03.20 |
Guides&Concepts_(Important Defaults) (0) | 2023.03.20 |
React Query (0) | 2023.01.12 |