⸻
프론트엔드에서 네트워크 중복 호출 방지 방법
1. isLoading 플래그 사용
let isLoading = false;
async function fetchData() {
if (isLoading) return;
isLoading = true;
try {
const res = await axios.get('/api/data');
console.log(res.data);
} finally {
isLoading = false;
}
}
⸻
2. Debounce / Throttle 적용 (lodash 사용)
import debounce from 'lodash.debounce';
const handleSearch = debounce((value) => {
axios.get(`/api/search?q=${value}`);
}, 300);
⸻
3. AbortController로 이전 요청 취소
let controller;
function fetchData(query) {
if (controller) controller.abort();
controller = new AbortController();
axios.get(`/api/search?q=${query}`, {
signal: controller.signal,
})
.then(res => console.log(res.data))
.catch(err => {
if (err.name === 'CanceledError') {
console.log('요청 취소됨');
}
});
}
⸻
4. 중복 요청 캐싱 Map
const pendingRequests = new Map();
function fetchOnce(url) {
if (pendingRequests.has(url)) return pendingRequests.get(url);
const promise = axios.get(url).finally(() => {
pendingRequests.delete(url);
});
pendingRequests.set(url, promise);
return promise;
}
⸻
5. React Query / SWR 활용
// React Query 예시
const { data, isLoading } = useQuery(['user', id], () => axios.get(`/api/user/${id}`));
⸻
6. 버튼 중복 클릭 방지
<button onClick={fetchData} disabled={isLoading}>
{isLoading ? '로딩 중...' : '불러오기'}
</button>
⸻
'CS' 카테고리의 다른 글
Axios CancelToken (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 |