이번 예시는 React Query v4 의 useQuery라는 훅의 Option인 queryFn을 예시로 살펴본다.
queyrFn는 promise를 반환하는 함수여야 한다. useQuery는 주로 데이터 fetching으로 사용하는데, 이를 위해 fetch 와 axios를 이용한 다양한 표현들을 알아보자.
각 api는 async/await 와 Promise chaining 을 사용하여 나타낼 수 있다.
참고로, axios와 fetch의 성능 차이는 크게 없으며, 아래 함수들의 return값은 모두 Promise{<pending>} 이다.
axios와 fetch의 성능 차이는 크게 없다.
다만, axios가 가독성이 더 좋고 사용할 수 있는 기능이 많기 때문에 더 선호되는 경향이 있다.
fetch는 웹 내장 함수이기 때문에 설치 없이 사용할 수 있다.
1) Axios + Promise chaining
export const coinsFetcher = () =>
axios.get("URL").then((res) => res.data);
2) Fetch + Promise chaining
export const coinsFetcher = () =>
fetch(`${BASE_URL}/coins`).then((res) => res.json());
# Promise chaining으로 작성하면 좀 더 간결한 코드를 작성할 수 있다.
3) Axios + async/await
export const coinsFetcher = async () => {
const { data } = await axios.get("URL");
return data;
};
4) Fetch + async/await
export const coinsFetcher = async () => {
const response = await fetch("URL");
const data = await response.json();
return data;
};
# async/await 으로 작성하면 가독성이 더 좋아진다.
5) Fetch + async/await + IIFE
export const coinsFetcher = async () => {
return (async () =>await (await fetch("URL")).json())();)
};
# IIFE는 코드가 간결해지지만, 가독성이 안 좋아지는 단점이 있다.
참고)
- https://tanstack.com/query/v4/docs/react/reference/useQuery
- https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Functions/Arrow_functions
'Front-end > JavaScript' 카테고리의 다른 글
JS) 배열의 얕은 복사와 깊은 복사 (0) | 2023.03.08 |
---|---|
JS) not not 연산자 vs non-null assertion 연산자 (0) | 2023.03.02 |
JS) then vs async/await ... (예시: fetch API) (0) | 2023.03.01 |
JS) fetch VS axios (API 호출) (0) | 2023.02.27 |
JS) [Alert] 웹 사이트에 경고 문구 띄우기 (0) | 2022.10.15 |