페이징 구현하기

 

const container = document.querySelector('#root');
const ajax = new XMLHttpRequest();
const NEWS_URL = 'https://api.hnpwa.com/v0/news/1.json'
const CONTENT_URL = 'https://api.hnpwa.com/v0/item/@id.json';
const store = {
    currentPage: 1,
}

function getData(url){    
    ajax.open('GET', url, false); // method, Url, async
    ajax.send();

    return JSON.parse(ajax.response);
}

function newsFeed(){
    const newsFeed = getData(NEWS_URL)
    const newsList = [];

    newsList.push('<ul>');
    
    for(let i=(store.currentPage - 1) * 10; i<store.currentPage * 10; i++){
        newsList.push(`
            <li>
                <a href="#/show/${newsFeed[i].id}">
                    ${newsFeed[i].title} (${newsFeed[i].comments_count})
                </a>
            </li>
        `);        
    }

    newsList.push('</ul>');
    newsList.push(`
        <div>
            <a href="#/page/${store.currentPage > 1 ? store.currentPage - 1 : 1}">이전 페이지</a>
            <a href="#/page/${store.currentPage + 1}">다음 페이지</a>
        </div>
    `)

    container.innerHTML = newsList.join('');
}

function newsDetail(){
    const id = location.hash.substring(7);

    const newsContent = getData(CONTENT_URL.replace('@id', id));
    const title = document.createElement('h1');        

    container.innerHTML = `
        <h1>${newsContent.title}</h1>
        <div>
            <a href="#/page/${store.currentPage}">목록으로</a>
        </div>
    `;
}

function router(){
    const routePath = location.hash;

    if(routePath === ''){
        newsFeed();        
    }else if(routePath.indexOf('#/page/') >= 0){
        store.currentPage = parseInt(routePath.substring(7));
        newsFeed();                
    }else{        
        newsDetail();
    }
}

window.addEventListener('hashchange', router);

router();

페이징 처리를 하기 위해서 전체적으로 공용으로 사용할 store라는 객체에 currentPage 값을 추가했다. 이 store 객체는 hacknews 페이지의 전역객체로 사용될 것이다. 리액트를 사용하면 상위 컴포넌트에서 하위 컴포넌트로 props를 통해 데이터를 전달하는데 리덕스를 사용하면 컴포넌트를 전역적으로 설정하고 다른 여러 컴포넌트에서 사용할 수 있다. 현재 만든 웹앱 구조의 store 객체의 컨셉은 리덕스처럼 사용될 것 같다. 지금은 단순 리터럴로 사용된 전역 객체지만 앞으로 약간의 변화를 통해 다른 객체들에서 전역적으로 작용할 객체가 될 것이다.

 

또한 페이징 처리를 할 url과 목록을 조회하는 url을 분리 시켰기 때문에 라우팅 처리를 해줘야하는 router 함수를 수정했다. hashchange 이벤트 리스너를 통해서 변화된 path에 따라 보여지는 화면이 newsFeed와 newsDetail로 나눠진다.

 

 

 

https://bit.ly/37BpXiC

 

패스트캠퍼스 [직장인 실무교육]

프로그래밍, 영상편집, UX/UI, 마케팅, 데이터 분석, 엑셀강의, The RED, 국비지원, 기업교육, 서비스 제공.

fastcampus.co.kr

 

본 포스팅은 패스트캠퍼스 환급 챌린지 참여를 위해 작성되었습니다.

 

#패스트캠퍼스 #패캠챌린지 #직장인인강 #직장인자기계발 #패스트캠퍼스후기 #김민태의프론트엔드아카데미:제1강JavaScript&TypeScriptEssential

'study' 카테고리의 다른 글

패스트캠퍼스 챌린지 13일차  (0) 2022.02.05
패스트캠퍼스 챌린지 12일차  (0) 2022.02.04
패스트캠퍼스 챌린지 10일차  (0) 2022.02.02
패스트캠퍼스 챌린지 9일차  (0) 2022.02.01
패스트캠퍼스 챌린지 8일차  (0) 2022.01.31

+ Recent posts