코드스테이츠에서 진행한 스프린트 입니다. 따라서 주어진 API만 활용할 수 있습니다.
client
와server
가 통신하는 과정에서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);
}
})
},
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);