npm i @tanstack/react-query
or
pnpm add @tanstack/react-query
or
yarn add @tanstack/react-query
tanstack query 공식문서에 코딩하는 동안 버그와 불일치를 잡는데 도움이 되도록 ESLint 플러그인 사용을 권장한다.
npm i -D @tanstack/eslint-plugin-query
or
pnpm add -D @tanstack/eslint-plugin-query
or
yarn add -D @tanstack/eslint-plugin-query
import React from 'react';
import ReactDOM from 'react-dom/client';
import App from './App.tsx';
import './index.css';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
const queryClient = new QueryClient();
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
</React.StrictMode>,
);
최상단 컴포넌트에 queryClient를 지정해주어야 한다. 나의 경우 main.tsx
에 적용
const result = useQuery({
queryKey, // required
queryFn, // required
// ...options ex) gcTime, staleTime, select, ...
});
result.data;
result.isLoading;
result.refetch;
// ...
v5
부터 인자로 단 하나의 객체만 받는다. 그 중에 첫 번째 인자가 queryKey
, queryFn
이 필수 값이다.// 실제 사용 예제
const getAllSuperHero = async (): Promise<AxiosResponse<Hero[]>> => {
return await axios.get("http://localhost:4000/superheroes");
};
const { data, isLoading } = useQuery({
queryKey: ["super-heroes"],
queryFn: getAllSuperHero,
});
배열
로 지정해줘야 한다.useQuery({queryKey:["todo"]})
useQuery({queryKey:["todo",5]})
useQuery는 querykey
를 기반으로 쿼리 캐싱
을 관리하는 것이 핵심
- 만약, 쿼리가 특정 변수에 의존한다면 배열에다 이어서 줘야 한다. ex: ["todo", todoId, ...]
queryKey의 경우 데이터를 고유하게 식별할 수 있다.
Promise
를 반환하는 함수를 넣어야 함.const Service = async (code: string, state: string) => {
try {
const res = await axios.get(`http://localhost:8081/api/v1/profile?code=${code}&state=${state}`);
return res.data;
} catch (error) {
console.error(error);
}
};
export const useSocialQuery = (code: string, state: string) => {
return useQuery({
queryKey: ['social', code, state],
queryFn: () => Service(code || '', state), // (*)
enabled: !!code && !!state,
});
};
const {
data,
error,
status,
fetchStatus,
isLoading,
isFetching,
isError,
refetch,
// ...
} = useQuery({
queryKey: ["super-heroes"],
queryFn: getAllSuperHero,
});
Promise
에서 resolved
된 데이터data
, 쿼리 결과값에 대한 상태를 표현하는 status는 문자열 형태로 3가지
의 값이 존재함.queryFn
에 대한 정보를 나타냄캐싱 된 데이터가 없을 때
즉, 처음 실행된 쿼리일 때 로딩 여부에 따라 true/false
로 반환false
를 반환true/false
로 반환true
true
import { useInfiniteQuery } from "@tanstack/react-query";
// useInfiniteQuery의 queryFn의 매개변수는 `pageParam`이라는 프로퍼티를 가질 수 있다.
const fetchColors = async ({
pageParam,
}: {
pageParam: number;
}): Promise<AxiosResponse<PaginationColors>> => {
return await axios.get(`http://localhost:8081/service?page=${pageParam}`);
};
const InfiniteQueries = () => {
const { data, hasNextPage, isFetchingNextPage, fetchNextPage } = useInfiniteQuery({
queryKey: ['service', size],
queryFn: ({ pageParam = 0 }) => service({ pageParam, size }),
initialPageParam: 0,
getNextPageParam: (lastPage, allPages) => {
if (!lastPage.last) {
return allPages.length;
}
return undefined;
},
});
return (
<div>
{data?.pages.map((group, idx) => ({
/* ... */
}))}
<div>
<button disabled={!hasNextPage} onClick={() => fetchNextPage()}>
LoadMore
</button>
</div>
<div>{isFetching && !isFetchingNextPage ? "Fetching..." : null}</div>
</div>
);
};
isFectingNextPage
, isFetchingPreviousPage
, fetchNextPage
, hasNextPage
등이 추가적으로 있음.TPageParam
필수값
(lastPage,allPages,lastPageParam, allPageParams) => TPageParam | undefined | null
자세한 내용은 여기 참고 바랍니다