public arraySuccess = [];
ngOnInit(): void {
this.arraySuccess = JSON.parse(localStorage.getItem('success'));
}
openDialog(String) {
this.dialog.open(RecommendationsDialog);
if(this.arraySuccess != null &&
this.arraySuccess.includes(String)) {
return
} else if (this.arraySuccess != null) {
this.arraySuccess.push(String);
}
localStorage.setItem('success', JSON.stringify(this.arraySuccess));
console.log(this.arraySuccess);
}
There are articles (3 pcs). When opening, I would like to add their name to the localstorage
. And if the user visits the page again, the read checkbox would be ticked. (checking if the given name is in the localstorage
array)
But the problem is that I get null
in the console.
Where did I make a mistake?
CodePudding user response:
Null value handling
Since localStorage.getItem() returns a value or null, you might want to ensure that arraySuccess is an array before calling the push method :
this.arraySuccess = JSON.parse(localStorage.getItem('success')) ?? [];
This way, even if it returns null, you'll save your element.
Also, declare your variable like so (instead of String) :
openDialog(myString: string) {
this.dialog.open(RecommendationsDialog);
if(this.arraySuccess.includes(myString)) {
return
} else {
this.arraySuccess.push(myString);
}
localStorage.setItem('success', JSON.stringify(this.arraySuccess));
}
Cheers
Edit: modified null handling thanks to Heretic Monkey