'Archive buttons need to be clicked twice for main page content to be changed in JavaScript

I am developing email website which relies on API. I have multiple divs with 2 buttons inside each of those divs: first - information of email body and second - archived/unarchived state. I am using for loop with a function to addEventListener on each of 2 buttons in every div. When they are clicked API info is modified and page is reloaded once more. It is a single html page so when mailbox is loaded, initially script does not know whether inbox, sent or archived mails should be displayed. I filter content displayed on page using conditions. The problem is that I need to click on archive button twice for unarchived content to move to archived and vise versa. I honestly have a hard time understanding why. Please, help me and if more code is needed, let me know!

function load_mailbox(mailbox) {
  console.log(mailbox);
  document.querySelector('#compose-view').style.display = 'none';
  document.querySelector('#emails-view').style.display = 'none';
  // Show the mailbox name
  document.querySelector('#emails-view').innerHTML = `<h3>${mailbox.charAt(0).toUpperCase() + mailbox.slice(1)}</h3>`;
  var emailsList = document.querySelector('#emails-view');
  fetch(`/emails/${mailbox}`)
    .then((response) => response.json())
    .then((emails) => {
      var buttons = document.createElement('div');
      buttons.id = "buttons";
      emails.forEach((email) => {
        var user =  document.querySelector('#user').value;
        var item = document.createElement('button');
        if (email.sender == user)
        {
          var fromto = "to: " + email.recipients;
        }
        else {
          var fromto = "from: " + email.sender;
        }
      if (mailbox == 'inbox' && email.sender == user || mailbox == 'sent' && email.sender != user || mailbox != 'archive' && email.archived == true)
      {
        item.remove();
      }
      else{
      if (email.archived == true) {
      item.innerHTML = `<button class="content" id=${email.id}> ${fromto}: ${email.subject}</button><button id = "archive" style="background-color:red;">unarchive</button>`
      }
      else {
      item.innerHTML = `<button class="content" id=${email.id}> ${fromto}: ${email.subject}</button><button id = "archive" style="background-color:#4CAF50;">archive</button>`
      }
      item.className = "button";
      buttons.appendChild(item);
      emailsList.appendChild(buttons);
    }
      });
      document.querySelector('#emails-view').style.display = 'block';
      var num = document.querySelector("#buttons").childElementCount;
      var button = document.querySelectorAll(`.button .content`);
      var archieve = document.querySelectorAll(".button #archive");
      for (i = 0; i < num; i++) {
        function listen (i) {
        archieve[i].addEventListener('click',  () => {
          if (archieve[i].innerHTML == "archive")
          {
            var state = true;
          }
          else {
            var state = false;
          }
          console.log(state)
          fetch(`/emails/${parseInt(button[i].id)}`, {
            method: "PUT",
            body: JSON.stringify({
              archived: state
            })
          },
          )
          load_mailbox(mailbox);
})
         button[i].addEventListener('click',  () => {
            fetch(`/emails/${parseInt(button[i].id)}`) 
            .then((response) => response.json())
                .then(result => {
        // Print result
        console.log(result);
        fetch(`/emails/${parseInt(button[i].id)}`, {
    method: "PUT",
    body: JSON.stringify({
      read: true
    })
  })
      })
        })} listen(i); 
      }
})
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source