npm i @tanstack/react-query
👾 index.tsx
import {
QueryClient,
QueryClientProvider,
} from '@tanstack/react-query'
// Create a client
const queryClient = new QueryClient();
root.render(
// Provide the client to your App
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
👾 api.tsx
export async function fetchCoins() {
return await (await fetch(`https://api.coinpaprika.com/v1/coins`)).json();
}
const {isLoading, data} = useQuery(["queryKey"],fetcher함수, arguments)
isLoading
: isLoading을 반환(boolean), 로딩이 완료되면 false를 반환.data
: fetcher함수에서 반환한 json데이터를 가리킨다.queryKey
: query의 고유식별자fetcher함수
: 2에서 만든 함수를 import해서 등록한다. 데이터를 받아오고 JSON을 리턴하는 함수arguments
: {refetchInterval:500}과 같이 fetch를 5초마다 실행되게 함.👾
import { useQuery } from "@tanstack/react-query"
interface ICoin {
id: string;
name: string;
symbol: string;
rank: number;
is_new: boolean;
is_active: boolean;
type: string;
}
...
const { isLoading, data: coins } = useQuery<ICoin[]>(["allCoins"], fetchCoins);
👾 fetcher함수에 인수 전달
const { isLoading: isLoadingInfo, data: info } = useQuery<InfoData>(["info", coinId], () => fetchCoinInfo(coinId));
npm i @tanstack/react-query-devtools
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
function App() {
return (
<QueryClientProvider client={queryClient}>
{/* The rest of your application */}
<ReactQueryDevtools initialIsOpen={true} />
</QueryClientProvider>
)
}