I have log set text and it is triggered 3 times why ? see behavior here https://jsfiddle.net/5kv2g6hc/
class Test {
set text(text) {
console.log(text); // 3 times ?!!!
this.text = text;
}
constructor() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
response.text().then((response) => {
this.text = response;
// console.log(this.text);
});
});
}
}
let test = new Test();
Actually, it's called more than 3 times. It's a recursive call.
It is first initialized in the promise handler by using this.text = response.
Then, within the setter you call this.text = text which basically triggers the same setter once again. And so it goes indefinitely (limited by V8 stack and stack overflow error is thrown).
When setters are used new props are created to store the value, because name of a getter/setter cannot be the same as the one storing the value.
So your code should be modified. There are two ways. The old one by using an underscore to tell that it's a private prop and shouldn't be used directly from the outside
class Test {
set text(text) {
console.log(text);
this._text = text; // <- here _text instead of text
}
constructor() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
response.text().then((response) => {
this.text = response;
// console.log(this.text);
});
});
}
}
let test = new Test();
And a new one which uses the new syntax of real private properties introduced in JS recently
class Test {
#text; // <- first, declare the private prop
set text(text) {
console.log(text);
this.#text = text; // <- then use #text instead of text
}
constructor() {
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then((response) => {
response.text().then((response) => {
this.text = response;
// console.log(this.text);
});
});
}
}
let test = new Test();