I have a chat program that adds an element to the dom when messaged. This element adds properly, but when I go to query it from the dom it shows as null. I do a fetch to the server just before, but it has an await to slow it down. Any ideas?
Here is my javascript code
socket.on('receive_message', async function(data) {
let messaged_user_li = document.getElementById('messaged_user_li' data['from_user']);
console.log('messaged_user_li: ' messaged_user_li)
if (messaged_user_li == null) {
console.log('if fired')
await fetch('/get_messaged_user/' data['from_user']).then((response) => {
response.json().then((data2) => {
loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
});
});
console.log(data['from_user'])
messaged_user_li = document.getElementById('messaged_user_li' data['from_user']);
//despite this element being added this log shows nulls which causes issues later on in the code.
console.log('messaged_user_li: ' messaged_user_li)
}
let message_user = document.getElementById('message_user' data['from_user']);
let message_target = document.getElementById("message_target" data['from_user']);
if (messaged_user_li.classList.contains('active') == false) {
messaged_user_li.classList.add('flash-message');
}
if (message_user != null) {
data = `
<li >
<div >
<span >just now</span>
</div>
<div >` data['message'] `</div>
</li>`;
message_target.innerHTML = data;
//Move scroller to bottom when message received
myDiv = message_user.querySelector(".chat-history");
myDiv.scrollTop = myDiv.scrollHeight;
}
});
CodePudding user response:
You are only waiting for this promise to complete:
await fetch('/get_messaged_user/' data['from_user']).then((response) => {
// ...
});
Not this one inside the callback:
response.json().then((data2) => {
loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);
});
Which is why your code continues executing and trying to get the added element (which hasn't been added yet).
To solve this, you could chain the then
calls:
await fetch('/get_messaged_user/' data['from_user'])
.then((response) => response.json())
.then((data2) => loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen));
Or use await
again:
const response = await fetch('/get_messaged_user/' data['from_user']);
const data2 = await response.json();
loadMessagedUser(data2[0].id, data2[0].avatar, data2[0].username, data2[0].last_seen);