Auto Fetching 구현

Judo·2020년 12월 25일
0

코드스테이츠에서 진행한 스프린트 입니다. 따라서 주어진 API만 활용할 수 있습니다.

구현하고자 한 기능


  • clientserver가 통신하는 과정에서 client에서 새로고침을 하지 않더라도 server에서 게속 새로운 메시지들을 받아 올 수 있게 구현하기

계획

  • setInterval을 사용한다.
  • 주기적으로 서버에 데이터를 확인하고 추가된 데이터가 있다면 해당 데이터를 브라우저로 보내기

수행

autoFetch: () => {
    
    fetch(app.server)
    .then(res => res.json())
    .then(json => {
	 
      let lastData = json.results[json.results.length - 1];//서버 가장 마지막 데이터를 가져온다.
      if (json.results.length - 1 !== app.database.length - 1) {//여기서 database는 페이지가 로드되고 새로운 메시지가 추가되기 전 서버에 데이터를 가져와 저장한 공간
        app.database = json.results;
        const $chats = document.querySelector('#chats');
        const $div1 = document.createElement('div');
        const $div2 = document.createElement('div');
        const $chat = document.createElement('div');
        $chat.classList.add('chat');
    
        $div1.textContent = lastData.username;
        $div1.classList.add('username');
          
        $div2.textContent = lastData.text;
        $chat.append($div1, $div2);
    
        $chats.prepend($chat);
      }
    })
  },

어려웠던 점

  • 추가된 데이터가 있는지 확인해야 하는데 어떻게 해야 추가된 데이터를 확인할지 떠오르지 않았다.
    mdn, stackoverflow에서 찾아봐도 실시간으로 카운트된다던지, 혹은 기본적인 fetch 사용법에 대해만 나와있어서 해결하지 못하고 있었다. 그러다가 서버 데이터의 마지막 길이를 데이터가 새로 추가된 서버 데이터의 길이 비교를 하자는 생각이 들었다.

해결

  • 새로운 데이터가 추가되기 전 서버를 저장해두기 위해 let database를 선언했다.
//서버에 있는 데이터를 가져오는 메서드 
  fetch: () => {
    fetch(app.server)
      .then(res => res.json())
      .then(json => {
        let messageArray = json.results.reverse();
        app.database = json.results;
        messageArray.forEach(app.renderAllMessage)

      })
  }
  • fetch는 페이지가 로드되면 가장 먼저 서버에 데이터를 가져오는 메소드다. 이를 이용해 데이터를 가져올 때 database에 가져온 데이터를 넣어둔다.
  • 이후 setInterval를 이용해 autoFetch메서드를 주기적으로 실행시켜준다. 그러면서 database.length와 메서드 실행 당시 서버에 데이터 길이(json.results.length)를 비교하여 길이가 다르다면 데이터가 추가된 것으로 보고 마지막 데이터를 DOM에 추가했다.
autoFetch: () => {
    
    fetch(app.server)
    .then(res => res.json())
    .then(json => {
	 
      let lastData = json.results[json.results.length - 1];//서버 가장 마지막 데이터를 가져온다.
      if (json.results.length - 1 !== app.database.length - 1) {//여기서 database는 페이지가 로드되고 새로운 메시지가 추가되기 전 서버에 데이터를 가져와 저장한 공간
        app.database = json.results;
        const $chats = document.querySelector('#chats');
        const $div1 = document.createElement('div');
        const $div2 = document.createElement('div');
        const $chat = document.createElement('div');
        $chat.classList.add('chat');
    
        $div1.textContent = lastData.username;
        $div1.classList.add('username');
          
        $div2.textContent = lastData.text;
        $chat.append($div1, $div2);
    
        $chats.prepend($chat);
      }
    })
  }
setInterval(app.autoFetch, 5000);
profile
즐거운 코딩

0개의 댓글