I am having this problem where it keeps saying Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '0')
when I am pretty sure this is right.
My response from the page the system is getting text from is here:
"[{u0027messageu0027: u0027amazingu0027, u0027sent_byu0027: u0027Tester Wupxu0027}, {u0027messageu0027: u0027wowu0027, u0027sent_byu0027: u0027Tester Wupxu0027}, {u0027messageu0027: u0027nameu0027, u0027sent_byu0027: u0027guestu0027}]"
Here is my code:
async function getNewMessages() {
await fetch(`/get_new_messages/s/${sId}`).then(async function(response) {
const body = await response.text();
arr = body.replace('[', "{'auto': [").replace(']', ']}')
console.log(arr)
json = await JSON.parse(arr);
document.querySelector('.channel-messages ul').innerHTML = null;
for (const i in Object.keys(json)) {
const obj = json["auto"][i];
document.querySelector('.channel-messages ul').insertAdjacentHTML('beforeend', `<li style="padding-left: 10px; color: white; width: 100%;" onmouseover="const collection = this.children; this.style.background = '#535357'; this.style.color = 'white';" onmouseout="const collection = this.children; this.style.background = 'transparent'; this.style.color = 'white';"><b><img src="/assets/images/Goobler-meowsicles.png" width=40/> <onclickFunc onclick="">${obj["sent_by"]}</onclickFunc> <span class="badge" style="background: mediumpurple;">TESTER <i class="fa fa-check"></i></span> </b> <br>${obj["message"]}</li>`);
console.log(obj)
}
/*document.querySelector('.channel-messages ul').insertAdjacentHTML('beforeend', `<li style="padding-left: 10px; color: white; width: 100%;" onmouseover="const collection = this.children; this.style.background = '#535357'; this.style.color = 'white';" onmouseout="const collection = this.children; this.style.background = 'transparent'; this.style.color = 'white';"><b><img src="/assets/images/Goobler-meowsicles.png" width=40/> <onclickFunc onclick="">${json.message}</onclickFunc> <span class="badge" style="background: mediumpurple;">TESTER <i class="fa fa-check"></i></span> </b> <br>${json["messages"]['message']}</li>`);*/
})
//location.reload()
} /*edited code*/
I appreciate answers!
3
Answers
I fixed it myself, I will explain what I did. I changed
await response.text()
toawait response.json()
instead. I edited the for loop Here is my code now:replace
u0027
withu0022
i.e. single quotes with double quotes as the single quote is not a valid JSON.Updated
If your
body
equals to this:Then try in this way: