API 요청 방식
- API를 호출할 땐 요청 도구와 응답 처리 방식을 조합해서 사용
요청 도구
- fetch
- 브라우저 내장 함수
- 별도 설치 불필요
- 작은 프로젝트나 간단한 요청에 적합
- axios
- 외부 라이브러리
- 응답 데이터가
res.data에 바로 담김
- 인터셉터, 기본 설정, 취소 토큰 등 부가 기능 풍부
응답 처리 방식
- Promise 체이닝 (then/catch)
- 간단한 코드에 적합
- 중첩이 많아지면 가독성 저하 가능
- async/await + try/catch
- 동기 코드처럼 작성 가능
- 가독성이 좋고 예외 처리 명확
사용 예제
1. fetch + then
fetch("https://api.example.com/data")
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error("에러 발생:", error);
});
2. axios + then
axios.get("https://api.example.com/data")
.then((res) => {
console.log("응답 데이터:", res.data);
})
.catch((err) => {
console.error("에러 발생:", err);
});
3. fetch + async/await
async function getData() {
try {
const response = await fetch("https://api.example.com/data");
const data = await response.json();
console.log("응답 데이터:", data);
} catch (error) {
console.error("에러 발생:", error);
}
}
getData();
4. axios + async/await
import axios from "axios";
async function getData() {
try {
const res = await axios.get("https://api.example.com/data");
console.log(res.data);
} catch (err) {
console.error("에러 발생:", err);
}
}
getData();
5. TanStack Query
- 서버 상태를 관리할 때 유용
- 자동 캐싱·로딩·에러 상태 관리 지원
import { useQuery } from "@tanstack/react-query";
import axios from "axios";
function ExampleComponent() {
const { data, isLoading, isError } = useQuery({
queryKey: ["exampleData"],
queryFn: async () => {
const res = await axios.get("https://api.example.com/data");
return res.data;
},
});
if (isLoading) return <p>로딩 중...</p>;
if (isError) return <p>에러 발생</p>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}