I have this simple constructor where I have a count variable in a state and a button that sums up the count by one when clicked. Here is the code:
import onChange from 'on-change';
import './style.css';
class App {
constructor() {
const state = {
count: 0,
}
this.state = onChange(state, this.update);
this.el = document.createElement('div');
//if the button is clicked, count sums up by one
this.btn = document.createElement('button');
this.btn.textContent = "Click Me!";
this.btn.addEventListener("click", e => {
this.state.count = this.state.count += 1;
})
this.el.appendChild(this.btn);
this.el.className = 'container';
}
update(path, current, previous) {
console.log(this.el); // prints undefined
}
}
const app = new App();
app.update(); //prints the div
document.body.appendChild(app.el);
However the problem is that when the state is updated, I try to console log 'this.el' which is a dom element, returns simply undefined. But when I call the update function directly, then it successfully prints the value. I do not know what I'm missing. Why is my (this.el) returns undefined in the update function which fires everytime that there is a change in state, but works when called directly outside of the constructor? Thank you very much.