0

JavaScript is new to me and as I come from OOP language I try to use classes in Js, but cannot understand why I get my callback deleteFromDom not called and either no error is shown.

class CarsOperations {
  deleteBtn() {
    let buttons = document.getElementsByClassName('btn-delete');

    [...buttons].forEach(b => b.addEventListener('click', this.deleteItem))
  }

  async deleteItem(event) {
    let btn = event.target;
    let id = btn.getAttribute('data-id');

    let lastSlashIndex = btn.baseURI.lastIndexOf('/');
    let baseUrl = btn.baseURI.substring(0, lastSlashIndex + 1);
    let fullUrl = baseUrl + 'delete/' + id;

    const httpMethod = "GET";

    const headers = {
      method: httpMethod,
      headers: {
        "Content-Type": "application/json"
      }
    };

    await fetch(fullUrl, headers)
      .then(e => {
        if (!e.ok) {
          throw new Error(e.statusText);
        }

        return e;
      })
      .then(this.deleteFromDom);
  }

  deleteFromDom(x) {
    if (x.status === 200) {

      console.log("function is called")
    }
    return x;
  }
}

let operations = new CarsOperations();
operations.deleteBtn();

The function deleteFromDom is never called after fetch() returns response? If there is no this. in front of callback deleteFromDom I get error deleteFromDom is not define, once I put this seems like deleteFromDom is found as a member of the class but it is never called?

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153

0 Answers0