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
CodePudding user response:
The smallest touch that will fix this is as follows:
- return the promise from the fetch
loadAllEntries(url) {
// just return, no further changes required
return fetch(url)
.then(...
- 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.