Today I Learned
변경 전
useEffect(() => {
const fetchProductList = async () => {
try {
if (categoryId) { // categoryId 값이 존재할 때에만 API 요청 보내도록 수정
const response = await axios.get(`http://localhost:8000/shop/products/list/${categoryId}`);
setProductList(response.data);
console.log(response.data)
} else { // categoryId 값이 존재하지 않을 경우 최신 상품 목록이 보여지도록 수정
const defaultResponse = await axios.get('http://localhost:8000/shop/products/list/recent/');
setProductList(defaultResponse.data);
console.log(defaultResponse.data)
}
} catch (error) {
console.error('Error fetching product list:', error);
}
};
fetchProductList();
}, [categoryId]);
useEffect(() => {
const fetchCategoryList = async () => {
try {
const response = await axios.get('http://localhost:8000/shop/categorys/list/');
setCategoryList(response.data);
} catch (error) {
console.error('Error fetching category list:', error);
}
};
fetchCategoryList();
}, []);
변경 후
useEffect(() => {
const fetchProductList = async () => {
try {
let url = 'http://localhost:8000/shop/products/list/';
if (categoryId) {
url += `${categoryId}/`;
}
const response = await axios.get(url);
setProductList(response.data);
console.log(response.data);
} catch (error) {
console.error('Error fetching product list:', error);
}
};
const fetchCategoryList = async () => {
try {
const response = await axios.get('http://localhost:8000/shop/categorys/list/');
setCategoryList(response.data);
} catch (error) {
console.error('Error fetching category list:', error);
}
};
fetchProductList();
fetchCategoryList();
}, [categoryId]);
개선사항 :
변경 전에는 fetchProductList 함수에서 categoryId 값의 유무에 따라 다른 URL을 사용하도록 분기 처리
변경 후에는 URL 통일을 위해 조건 분기를 제거하고, 카테고리 ID가 존재하지 않을 경우 최신 상품 목록을 가져오도록 설정
url 통일하는 것의 중요성! 중복을 줄이고 코드가 훨씬 간결해짐
또한 의존성 배열을 잘 설정하여 필요한 경우에만 API 요청을 보내도록 하는 것도 중요
'내일배움캠프 > 내일배움캠프 TIL' 카테고리의 다른 글
내일배움캠프 TIL 70일차 - 백엔드에서 페이지네이션 처리 (0) | 2023.06.19 |
---|---|
내일배움캠프 TIL 69일차 - 예외처리 해결 (0) | 2023.06.16 |
내일배움캠프 TIL 67일차 - 테스트코드 다중이미지 업로드 (2) | 2023.06.13 |
내일배움캠프 66일차 TIL - DRF 설정 및 권한 오류 (0) | 2023.06.13 |
내일배움캠프 65일차 TIL - 리액트로 프론트 구현하기 (1) | 2023.06.11 |