useQuery
- 첫번째 파라미터: unique key를 포함한 배열이 들어간다. 해당 키는 이후 동일한 쿼리를 불러올 때 유용하게 사용된다
- 두번째 파라미터: 실제 호출하고자 하는 비동기 함수, promise
- 최종 반환 값은 API의 성공, 실패 여부 반환값을 포함한 객체이다
example
import {
QueryClient,
QueryClientProvider,
useQuery,
} from '@tanstack/react-query'
const queryClient = new QueryClient()
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<Example />
</QueryClientProvider>
)
}
function Example() {
const { isLoading, error, data } = useQuery({
['repoData'],
() => axios.get('/user').then(
(res) => res.json()),
})
if (isLoading) return 'Loading...'
if (error) return 'An error has occurred: ' + error.message
return (
<div>
<h1>{data.name}</h1>
<p>{data.description}</p>
</div>
)
}
pueryKey:
- useQuery마다 부여되는 unique key값
- 문자열로 사용될 수도 있고, 배열의 형태로도 사용될 수 있음
- 배열에 입력되는 순서 보장
- 캐싱을 관리할 수 있도록 도와준다
const res = useQuery('persons', queryFn);
const res = useQuery(['persons'], queryFn);
const res = useQuery(['persons', 'add Id'], queryFn);
const res = useQuery(['add Id', 'persons'], queryFn);
const res = useQuery(['persons', {type: 'add', name: 'Id'}], queryFn);
- 설명1: 아래 코드에서는 res1에서 전달하게 되면 2에서는 이미 동일한 키에 대한 결과값이 있기 때문에 추가요청을 하지 않고 1의 결과를 그대로 가져와 사용하기 때문에 서버에 1개의 요청만 전달이 된다.
- 설명2: queryFn이 다르게 정의되어 있더라도 2에서는 1의 결과를 그대로 전달받기 때문에 queryFn1이 처리된 결과를 확인할 수 있다
import * as React from 'react';
import axios from 'axios';
import { useQuery } from 'react-query';
const Query = (): JSX.Element => {
const getPersons1 = () => {
const res1 = useQuery(['persons'], queryFn1);
}
const getPersons2 = () => {
const res2 = useQuery(['persons'], queryFn2);
}
return (
<div>
{getPersons1()}
{getPersons2()}
</div>
)
}
export default Query;
queryFn :
- promise 처리가 이루어지는 함수
const res = useQuery(['persons'],
() => axios.get('http://localhost:8080/persons'));
const res = useQuery({
queryKey: ['persons'],
queryFn: () => axios.get('http://localhost:8080/persons')
});
- 쿼리 자동 실행 설정. 조건이 맞을 때만 서버에 데이터 요청
const res = useQuery(['person', id], () => axios.get('http://localhost:8080/person', {
params: {
id: id,
}
}), {
enabled: !!id
});
const res1 = useQuery({
queryKey: ['person', id],
queryFn: () => axios.get('http://localhost:8080/person', {
params: {
id: id,
}
}),
enabled: !!id
});
useMutation
- 데이터 변경 작업할 때 사용
- post, update
useInfiniteQuery
- 파라미터값만 변경하여 동일한 useQuery를 무한정 호출할 때 사용
- 대표적인 예시로 infinite scroll이 있음
- useQuery와 동일하게 사용
const res = useInfiniteQuery(
['infinitePerson'],
({ pageParam = 5}) =>
axios.get('http://localhost:8080/person', {
params: {
id: pageParam
}
}));
getNextPageParam & fetchNextPage
- 다음 페이지에 있는 데이터를 조회해올 때 사용
getNextPageParam
- 파라미터 값으로 크게 lastPage, allPages 값을 전달받을 수 있다
- lastPage는 useInfiniteQuery를 이용해 호출된 가장 마지막에 있는 페이지 데이터를 의미
- allPages는 useInfiniteQuery를 이용해 호출된 모든 페이지 데이터를 의미
- lasePage에 있는 데이터의 id값보다 1 더 큰 값을 return값으로 하여 다음페이지가 호출될 수 있도록 할 수 있다
const res = useInfiniteQuery(
['infinitePerson'],
({ pageParam = 5 }) => axios.get('http://localhost:8080/person', {
params: {
id: pageParam
}
}), {
getNextPageParam: (lastPage, allPages) => {
return lastPage.data.id + 1;
},
});
fetchNextPage
- useInfiniteQuery의 return값에 포함되며 버튼을 클릭할 때 실행될 이벤트로 등록해줄 수 있다
<button onClick={() => res.fetchNextPage()}>Next</button>
getPreviousPageParam & fetchPreviousPage
- 이전 페이지에 있는 데이터를 조회해올 때 사용
참고블로그