Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

350
Views
How to change the contents of a class construcor in a javascript class and access it later?

Edit: I have a demo here

I want to fetch data from an API, add it to the constructor of a class, and then on button Click display it to the page.

class Entry {
  constructor() {
    this.pages = [];
  }
  loadAllEntries(url) {
    fetch(url)
      .then((response) => response.json())
      .then((data) => {
        this.pages = data;
        // this would do it autuomatically, it's not what I want
        //this.displayAllEntries("#notes-list");
      });
  }

  displayAllEntries(node) {
    let ul = document.createElement("ul");
    ul.id = "display-list-note";
    this.pages.map((page) => { 
      let li = document.createElement("li");
      li.innerText = page.title;
      ul.appendChild(this.createClickableItem(page));
    });
    document.querySelector(node).appendChild(ul);
  }
  createClickableItem(item) {
    let li = document.createElement("li");
    li.innerText = item.title;
    li.addEventListener("click", () => {
        console.log(item.id);
    });
    return li;
  }
}

const courses = new Entry();
courses.loadAllEntries("http://localhost:1338/courses?favorite=true");

// on some click I want to run 

courses.displayAllEntries("#notes-list");

But, displayAllEntries acts as if loadAllEntries never ran!

later on I want to do something like courses.deleteEntry(213) and change the contents of the constructor, (a glorified todo list type of thing)

Edit: I have a demo here

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The smallest touch that will fix this is as follows:

  1. return the promise from the fetch
    loadAllEntries(url) {
      // just return, no further changes required
      return fetch(url)
        .then(...
  1. At the top level, carry on after the fetch is done with then
const courses = new Entry();
const url = "http://localhost:1338/courses?favorite=true";
courses.loadAllEntries(url).then(() => {
  courses.displayAllEntries("#notes-list");
});

If the underlying methods work, this will work.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!