I'm having trouble with understanding how forEach function works. I'm trying to get the sender, subject and timestamp keys from an API and populate my html with that information for each email in the inbox. However, I'm getting Uncaught (in promise) TypeError: Cannot read properties of undefined ..
error no matter what I tried.
Should I use for loop instead of for Each? What seems to be the problem here?
inbox.js:
document.addEventListener('DOMContentLoaded', function() {
// Use buttons to toggle between views
document.querySelector('#inbox').addEventListener('click', () => load_mailbox('inbox'));
document.querySelector('#sent').addEventListener('click', () => load_mailbox('sent'));
document.querySelector('#archived').addEventListener('click', () => load_mailbox('archive'));
});
function load_mailbox(mailbox) {
// GET the mailbox
fetch(`/emails/${mailbox}`)
.then(response => response.json())
.then(emails => {
// Print emails
console.log(emails);
// ... do something else with emails ...
emails.forEach(email => {
const sender = emails.email.sender
document.querySelector("#email-sender").innerHTML = sender;
const subject = emails.email.subject
document.querySelector("#email-subject").innerHTML = subject;
const timestamp = emails.email.timestamp
document.querySelector("#email-timestamp").innerHTML = sender;
});
});
}
inbox.html:
<div id="emails-view">
<div >
<div id="email-sender">From:</div>
<div id="email-subject">Subject:</div>
<div id="email-timestamp">Time:</div>
</div>
</div>
API response:
[
{
"id": 100,
"sender": "[email protected]",
"recipients": ["[email protected]"],
"subject": "Hello!",
"body": "Hello, world!",
"timestamp": "Jan 2 2020, 12:00 AM",
"read": false,
"archived": false
}
]
CodePudding user response:
The error is in here
emails.forEach(email => {
const sender = emails.email.sender
document.querySelector("#email-sender").innerHTML = sender;
// ...
});
You are not using the email
variable but, instead, you are trying to access an email
key that does not exists in emails
, since it is your array.
Assuming that emails
is your array (just console.log
it, it should be an array, as expected), what you should do is just
emails.forEach(email => {
const sender = email.sender
document.querySelector("#email-sender").innerHTML = sender;
// ...
});
CodePudding user response:
Make sure the emails
variable is an array or something JS can loop through.
If you try to loop through something that JS cannot, then it will mark it as undefined.
I have also noticed that you put console.log(emails);
Look at this to see if the emails
variable even exists (or has data), or if it can be looped through.