프로그래머스에서 진행하는 자바스크립트 스터디에 참여, 학습한 내용을 적은 글입니다.
참여 스터디: [17기] 프론트엔드 개발을 위한 자바스크립트(feat. VanillaJS), 2022.09 - 2022. 10 (4주)
https://school.programmers.co.kr/learn/courses/15244
스터디 전체 회고는 1편 스터디 회고에 작성했습니다.
// ./js/App.js
this.updateSearchResult = async (keyword) => {
if (!keyword.length) return;
const requestURL = `${SEARCH_API_END_POINT}?keyword=${keyword}`;
const result = await request(requestURL);
searchResult.render(result);
};
// ./js/utils.js
const request = async (url) => {
try {
const res = await fetch(url);
if (!res.ok) {
throw new Error('서버에서 준 응답이 올바르지 않습니다.');
}
return res.json();
} catch (error) {
console.log('일시적인 오류로 응답하지 않습니다. 다시 요청해주세요.');
}
};
setTimeout
를 사용해 디바운스를 구현했다.const debounce = (func, delay) => {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => func(...args), delay);
};
};
// ./js/App.js
const searchInput = new SearchInput({
// input 입력시에만 디바운스 적용
handleKeyUp: debounce((keyword) => {
this.updateSearchResult(keyword);
searchHistory.setState(keyword);
}, 300),
});
const searchHistory = new SearchHistory({
handleHistoryClick: (keyword) => {
this.updateSearchResult(keyword);
searchInput.render(keyword);
},
});
const searchResult = new SearchResult({
handleMusicianClick: (keyword) => {
this.updateSearchResult(keyword);
searchInput.render(keyword);
},
});
SearchHistory
컴포넌트로 검색 기록 데이터를 로컬스토리지로 관리한다.setState
의 역할은 인자로 받는 state를 검증하고 변경, 렌더함수 호출인데 현재 내 코드는 키워드를 받아서 state를 만드는 일까지 하고 있었다. setState
를 호출하는 곳에서 nextState
를 만들어서 호출하는 형태로 변경을 해야 한다.nextState
를 반환하는 역할을 함수로 분리했다.setState
함수는 수정하지 않아도 되는 이점이 생긴 것 같다.// SearchHistory.js
//...
this.generateState = (searchKeyword) => {
if (!searchKeyword.length) return;
const addedHistory = [...new Set([...this.getState(), searchKeyword])];
const nextState =
addedHistory.length > 5 ? addedHistory.slice(1, 6) : addedHistory;
return nextState;
};
this.setState = (nextState) => {
this.validateState(nextState);
setLocalStorage(STORAGE_KEY, nextState);
this.render();
};
//...
// App.js
//...
const searchInput = new SearchInput({
handleKeyUp: debounce((keyword) => {
this.updateSearchResult(keyword);
const newHistoryState = searchHistory.generateState(keyword);
searchHistory.setState(newHistoryState);
}, 300),
});
promise를 다시 한 번 제대로 학습할 수 있는 시간이었다. 코드 리뷰에서 함수의 역할 분리에 관한 피드백을 자주 받았는데 코드를 작성할 때 신경쓴다고 해도 놓치는 것들이 있다. 단순히 신경쓰는게 아닌 단계적으로 확인할수 있는 루틴을 생각해봐야겠다.