I am working on CS50W's Mail project, and I struggle to understand how to update button's value without reloading the page. User should be able to archive and unarchive any emails he has been sent, and the button should change respectively: if the email is archived, it should say "Unarchive", and vice versa.
To do so, I created a condition, which would adjust button's innerHTML upon its creation in load_email():
// Fetch clicked email's data
fetch(`emails/${id}`)
.then(response => response.json())
.then(email => {
// Add content to the new elements
if (email.archived) {
archive_button.innerHTML = "Unarchive";
} else {
archive_button.innerHTML = "Archive";
}
As you can tell from the code above, I first fetch some date from the provided API, and then create a button. It works fine, but I also want to update the data in archive_email(email):
// Mark as archived or unarchived and show user's inbox
fetch(`/emails/${email.id}`, {
method: 'PUT',
body: JSON.stringify({
archived: !email.archived
})
})
.then(setTimeout(() => {
load_mailbox("archive");
}, 100)
);
Here I PUT the new value for archived, and load the mailbox of sent emails. Once I actually open the email, button's value stays the same. If I update the page, however, it'd change.
I ran the same code with adding console.log(email.archived); to load_email(), and it would display the value correctly, so the problem is with the representation, rather than with the data itself.
I'd really appreciate any help with understanding why the value wouldn't update without reloading the page.