React-Query 2

mopevxw·2022년 5월 17일
0

타입스크립트

목록 보기
7/11

react-query 적용 이전 Coin.tsx

const [loading, setLoading] = useState(true);
const { coinId } = useParams();
const { state } = useLocation() as RouteState;
const [info, setInfo] = useState<InfoData>();
const [priceInfo, setPriceInfo] = useState<PriceData>();
const priceMatch = useMatch("/:coinId/price");
const chartMatch = useMatch("/:coinId/chart");

useEffect(() => {
	(async () => {
		const infoData = await (
			await fetch(`https://api.coinpaprika.com/v1/coins/${coinId}`)
			).json();
      
		const priceData = await (
			await fetch(`https://api.coinpaprika.com/v1/tickers/${coinId}`)
			).json();
		setInfo(infoData);
		setPriceInfo(priceData);
      	setLoading(false);
		})();
	},[coinId]);

react-query 적용 이후 Coin.tsx
-isLoading, data 중복 방지 -> isLoading : infoLoading / isLoading:tickersLoading
-useQuery 두 번째 인자로 함수 자체 전달(실행x)

const { isLoading: infoLoading, data: infoData } = useQuery<InfoData>(
  ["info", coinId],
  () => fetchCoinInfo(coinId)
);
const { isLoading: tickersLoading, data: tickersData } = useQuery<PriceData>(
  ["tickers", coinId],
  () => fetchCoinTicker(coinId)
);
const loading = infoLoading || tickersLoading;

api.tsx

export function fetchCoins() {
return fetch(`${BASE_URL}/coins`).then(response =>
  response.json()
);
}
export function fetchCoinInfo(coinId: string | undefined) {
return fetch(`${BASE_URL}/coins/${coinId}`).then(response =>
  response.json()
);
}
export function fetchCoinTicker(coinId: string | undefined) {
return fetch(`${BASE_URL}/tickers/${coinId}`).then(response =>
  response.json()
);
}

리액트 쿼리 실행화면
<ReactQueryDevtools initialIsOpen={true}/>App.tsx에 추가

0개의 댓글