[스터디] #5 (크립토 트래커 클론) - React Query

ch9eri·2022년 9월 27일
0

React Query

React 애플리케이션에서 서버 state를 fetching, caching, synchronizing, updating할 수 있도록 도와주는 라이브러리

"global state"를 건드리지 않고 React 및 React Native 애플리케이션에서 데이터를 가져오고, 캐시하고, 업데이트한다

useQuery (queryKey, fetcher 함수)

const { isLoading, data } = useQuery("allCoins", fetchCoins);

fetcher 함수 부름

→ fetcher함수가 loading 중이라면 react query가 알려줌

→ fetcher함수 끝나면 api.ts 의 json을 data에 넣음

//api.ts
export function fetchCoins() {
    return fetch('https://api.coinpaprika.com/v1/coins').then((response) => response.json()
    );
}
function Coins() {
  const { isLoading, data } = useQuery<ICoin[]>(['allCoins'], fetchCoins);
}
//   const [coins, setCoins] = useState<CoinInterface[]>([]);
  //   const [loading, setLoading] = useState(true);
  //   useEffect(() => {
  //     (async () => {

  //       setCoins(json.slice(0, 100));
  //       setLoading(false);
  //     })();
  //   }, []);

뒤로 가기 해도 로딩 없는 이유

: react query가 데이터를 캐시에 저장해두기 때문


React Query Devtools

React Query의 모든 내부 작동을 시각화하는 데 도움이 되며 문제가 발생하면 디버깅 시간을 절약할 수 있다

Query Keys

핵심적으로 React Query는 쿼리 키를 기반으로 쿼리 캐싱을 관리합니다. 쿼리 키는 문자열처럼 단순할 수도 있고 많은 문자열과 중첩 개체의 배열처럼 복잡할 수도 있다

ex) const result = useQuery(['todos', todoId], () => fetchTodoById(todoId));

https://react-query.tanstack.com/guides/query-keys#_top

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

✅ solve)

const { isLoading: infoLoading, data: infoData } = useQuery(
["info", coinId],

() => fetchCoinInfo(coinId!)

);

const { isLoading: tickersLoading, data: tickersData } = useQuery(

["tickers", coinId],

() => fetchCoinTickers(coinId!)

);

이렇게 coinId 뒤에 !만 넣어줬더니 해결

!=> 확장 할당 어션셜로 값이 무조건 할당되어있다고 컴파일러에게 전달해 값이 없어도 변수를 사용할 수 있게 한다

profile
잘하자!

0개의 댓글