My goal is to create a single page email application with Javascript and HTML. The web framework I'm using is Django and according to the project guidelines, I should only be writing JS and HTML(so we can assume everything but my JS and HTML is correct).
My issue is that after I compose an email in the "compose" section of my app, I should be sent directly to the "sent" section where I can see all the emails I've sent including the one I just sent. For some reason, I'm unable to see the email I just sent. Only when I reload the page does it appear, which is not what I want. The below two snippets of code belongs to a file called inbox.js:
compose_email
function compose_email() {
// Show compose view and hide other views
document.querySelector("#emails-view").style.display = "none";
document.querySelector("#compose-view").style.display = "block";
const recipients = document.querySelector("#compose-recipients");
const subject = document.querySelector("#compose-subject");
const body = document.querySelector("#compose-body");
// Clear out composition fields
recipients.value = "";
subject.value = "";
body.value = "";
document.querySelector("form").onsubmit = function () {
const recipients = document.querySelector("#compose-recipients").value;
const subject = document.querySelector("#compose-subject").value;
const body = document.querySelector("#compose-body").value;
fetch("/emails", {
method: "POST",
body: JSON.stringify({
recipients: recipients,
subject: subject,
body: body,
}),
})
.then((response) => response.json())
.then((result) => {
//result is just a message to let me know if the email was sent successfully
console.log(result);
});
load_mailbox("sent");
return false;
};
}
load_mailbox
function load_mailbox(mailbox) {
// Show the mailbox and hide other views
document.querySelector("#emails-view").style.display = "block";
document.querySelector("#compose-view").style.display = "none";
// Show the mailbox name
document.querySelector("#emails-view").innerHTML = `<h3>${
mailbox.charAt(0).toUpperCase() + mailbox.slice(1)
}</h3>`;
//this is where I'm having issues
if (mailbox === "sent") {
fetch("/emails/sent")
.then((response) => response.json())
.then((emails) => {
//when I console.log(emails) after being directly sent to this function by compose_email I get an array that does not have the email I just sent.
console.log(emails);
for (var email of emails) {
document.querySelector("#emails-view").innerHTML += `
<div class="card bg-light">
<div class="card-body">
<div class="row">
<div class="col-4">${email.recipients}</div>
<div class="col-4">${email.subject}</div>
<div class="col-4">${email.timestamp}</div>
</div>
</div>
</div>
`;
}
});
}
}