I am creating a simple chat room and am expecting the page to update when I enter a message into a text box and press enter.
The room is receiving messages from a URL, but I have to reload the page to see my new message whenever I post it.
How do I display these messages without having to reload the page?
fetch GET:
fetch('https://curriculum-api.codesmith.io/messages', { 'method': 'GET' })
.then(response => response.json())
.then(data => addText(data))
fetch POST:
textBox.addEventListener('keydown', (e) => {
if (e.code === 'Enter') {
const func = async function postReply() {
const currentDate = new Date()
const message = textBox.value;
textBox.value = ''
return await fetch('https://curriculum-api.codesmith.io/messages',
{
method: 'POST',
body: JSON.stringify({
'message': message,
'created_at': currentDate.toUTCString(),
'created_by': 'Nate & Dewey'
})
})
.then(response => response.json())
// .then(json => addText(json.message))
}
func()
// $('#result').load('https://curriculum-api.codesmith.io/messages');
}
})
addText() function (used by GET)
function addText(data) {
let messageNum = 0
let current = data[messageNum]
while (current) {
const text = document.createElement('div');
border.appendChild(text);
text.innerText = current.message + ' (' + current.created_by + ')'
messageNum++
current = data[messageNum]
}
}