When working with local storage, I have a function that saves certain values and another method that reloads these values. However, what is the best approach to handle missing items in the local storage? This could happen if a user deletes an item or if it simply doesn't exist. The methods for getting and setting the local storage coordinates are as follows:
get savedValues(): { val1: number, val2: number, val3: number }[] {
if (localStorage.getItem('savedValues') === null) {
console.log("null");
return null;
}
return JSON.parse(localStorage.getItem('savedValues'));
}
set savedValues(value: { val1: number, val2: number, val3: number }[]) {
localStorage.setItem('savedValues', JSON.stringify(value));
}
This next method demonstrates how the coordinates are reloaded from the local storage:
reload(): void {
try {
for (var i = 0; i < this.savedValues.length; i++) {
this.oldValues[i].val1 = this.savedValues[i].val1;
this.oldValues[i].val2 = this.savedValues[i].val2;
this.oldValues[i].val3 = this.savedValues[i].val3;
}
}
catch (Exception) {
console.log("savedValuesitem is null in the local storage");
}
}
What is the correct way to try catching exceptions related to null fields in the local storage? I have also attempted:
if (this.savedValues !== null) {...}
However, this approach seems to be inefficient when checking the local storage.