한 번씩 잊어먹어서 메모처럼 정리해보기로!
동시에 Promise와 async/await의 작성 방식도 복습하자
JavaScript의 API 데이터 가져오는 방법
(1) XMLHttpRequest
오래된 방법..! 사용 경험이 없어 낯설지만 기록해둔다.
let xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.example.com", true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 & xhr.status === 200) {
let responseData = JSON.parse(xhr.responseText);
console.log(responseData);
}
}
xhr.send();
(2) Fetch API
익숙한 방식! GET 방식으로 API 데이터를 가져오는 방법은 아래와 같다.
요청이 성공할 경우 response 객체를 받아 json 형태로 파싱한다.
요청이 실패해 에러가 발생할 경우 catch에서 처리한다.
Promise 체인
fetch("https://api.example.com")
.then(response => response.json())
.then(data => console.log(data));
.catch(error => console.log(error));
함수형 + async/await
async function fetchData() {
try {
const response = await fetch("https://api.example.com");
const data = await response.json();
console.log(data);
} catch (error) {
console.error(error);
}
}
fetchData();
(3) Axios
Axios는 HTTP 요청을 보내는데 도움을 주는 라이브러리이다. (공식문서)
fetch와 유사하게 요청이 성공할 경우 response 객체를 받아 response.data로 받는다.
요청이 실패해 에러가 발생할 경우 catch에서 처리한다.
Promise
const axios = require("axios");
axios.get("https://api.example.com")
.then(response => console.log(response.data));
.catch(error => console.log(error));
함수형 + async/await
const axios = require("axios");
async function fetchData() {
try {
const response = await axios.get("https://api.example.com");
console.log(response.data);
} catch (error) {
console.error(error);
}
}
fetchData();
위 중 Fetch API나 Axios 사용이 권장되고 있다.
둘 다 Promise 기반이라 비동기 코드를 더 편리하게 작성할 수 있다는 점과
브라우저 및 Node.js 환경에서 모두 사용할 수 있어 유연성이 높다는 장점을 갖는다.
React의 API 데이터 가져오는 방법
(1) useEffect + Fetch API
컴포넌트가 마운트되는 단 한 번만 실행되도록 하기 위해 useEffect 훅을 사용한다.
가져와진 데이터는 컴포넌트의 상태로 저장된다
Promise
const [data, setData] = useState(null);
useEffect(() => {
function fetchData() {
fetch("https://api.example.com")
.then(response => { return response.json(); })
.then(json => { setData(json); })
.catch(error => { console.log(error); });
}
fetchData();
}, []);
async/await
const [data, setData] = useState(null);
useEffect(() => {
async function fetchData() {
try {
const response = await fetch("https://api.example.com");
const json = await response.json();
setData(json);
} catch(error) {
console.log(error);
}
};
fetchData();
}, []);
즉시 실행 함수(IIFE) : 함수를 정의하고 즉시 실행
const [data, setData] = useState(null);
useEffect(() => {
(async () => {
try {
const response = await fetch("https://api.example.com");
const json = await response.json();
setData(json);
} catch(error) {
console.log(error);
}
})();
}, []);
error catch 과정 생략 + fetch와 json 한 번에 작성
const [data, setData] = useState(null);
useEffect(() => {
(async () => {
const json = await (
await fetch("https://api.example.com")
).json();
setData(json);
})();
}, []);
(2) React-query + Fetch API
API 요청 작업을 쉽게 해주는 라이브러리 React Query 를 이용하는 방법도 있다.
(React Query 관련 포스팅 📚 [REACT] React Query(TanStack Query) 직접 적용해보며 알아가기)
async/await
async function fetchData() {
const response = await fetch("https://api.example.com");
return response.json();
}
/* ... 컴포넌트 내부 ... */
const { data, error, isLoading } = useQuery("myQueryKey", fetchData);
Promise
function fetchData() {
return fetch("https://api.example.com")
.then((response) => response.json());
}
/* ... 컴포넌트 내부 ... */
const { data, error, isLoading } = useQuery("myQueryKey", fetchData);
'REACT' 카테고리의 다른 글
[FIREBASE][REACT] Firestore 데이터베이스 가져오기. getDoc과 onSnapshot의 차이는? (1) | 2023.12.30 |
---|---|
[REACT] 리액트 앱 성능 개선! React.lazy를 이용한 코드 스플리팅 (0) | 2023.12.19 |
[REACT] React Query(TanStack Query) 직접 적용해보며 알아가기 (0) | 2023.11.14 |
[REACT] React Hooks 탐구하기 (0) | 2023.10.15 |
[REACT] createGlobalStyle 안에서 @import 사용 경고 해결하기 (0) | 2023.10.01 |