Axios CancelToken이란? (그리고 대체 방법)
HTTP 요청을 보내는 라이브러리인 Axios는 특정 요청을 취소(cancel) 할 수 있는 기능을 제공합니다. 이 기능은 다음과 같은 상황에서 매우 유용합니다:
• 검색창 자동완성처럼 빠르게 여러 요청이 발생할 때
• React 컴포넌트가 언마운트될 때
• 중복된 요청을 방지하고 싶을 때
⸻
1. CancelToken 기본 사용법
Axios에서는 CancelToken.source()를 이용해 요청을 취소할 수 있습니다.
import axios from 'axios';
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
axios.get('/api/data', {
cancelToken: source.token,
})
.then(response => {
console.log('요청 성공:', response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('요청이 취소되었습니다:', error.message);
} else {
console.error('요청 중 에러 발생:', error);
}
});
// 필요할 때 요청 취소
source.cancel('사용자가 요청을 취소했습니다.');
⸻
2. 왜 CancelToken을 쓸까?
예를 들어, 사용자가 검색창에 빠르게 글자를 입력하면 매번 요청이 발생하죠. 이때 이전 요청을 취소하지 않으면 불필요한 네트워크 낭비가 발생할 수 있습니다.
// input 이벤트마다 새로운 요청을 보내기 전에 이전 요청 취소
if (source) {
source.cancel('이전 요청 취소');
}
source = axios.CancelToken.source();
axios.get('/api/search?query=example', {
cancelToken: source.token
});
⸻
3. CancelToken은 Deprecated! 이제는 AbortController를 쓰자
CancelToken은 Axios 1.0부터 더 이상 권장되지 않습니다. 대신 브라우저의 표준 API인 AbortController를 사용하는 방식이 도입됐어요.
✅ 최신 방식: AbortController 사용 예제
const controller = new AbortController();
axios.get('/api/data', {
signal: controller.signal
})
.then(response => {
console.log('요청 성공:', response.data);
})
.catch(error => {
if (error.name === 'CanceledError') {
console.log('요청이 취소되었습니다');
} else {
console.error('요청 중 에러 발생:', error);
}
});
// 요청 취소
controller.abort();
'CS' 카테고리의 다른 글
프론트엔드에서 네트워크 중복 호출 방지 (0) | 2025.04.02 |
---|---|
직렬화 (0) | 2025.02.24 |
React server component (0) | 2025.02.24 |
[React Native] Pressable 컴포넌트 (1) | 2025.01.31 |
[React Native] Metro Bundler (2) | 2024.12.15 |