In this code I am getting error as Uncaught TypeError: Cannot read properties of null (reading 'push')
console.log("HI");
let addbtn = document.getElementById("addbtn");
addbtn.addEventListener("click", function (e) {
let addtxt = document.getElementById("addtxt");
let notes = localStorage.getItem("notes");
if (notes == null) {
notesObj = [];
} else {
notesObj = JSON.parse(notes);
}
notesObj.push(addtxt.value);
//getting error at this point. Don't know why
localStorage.setItem("notes", JSON.stringify(notesObj));
addtxt = "";
console.log(notesObj);
});
checkout this I hope it will fix your problem
let addbtn = document.getElementById("addbtn");
console.log('addbtn ', addbtn);
addbtn?.addEventListener("click", function (e) {
let addtxt = document.getElementById("addtxt");
let notes = localStorage.getItem("notes");
notesObj = JSON.parse(notes ?? '[]');
console.log('addtxt.value ', addtxt?.value);
notesObj.push(addtxt.value);
//getting error at this point. Don't know why
localStorage.setItem("notes", JSON.stringify(notesObj));
addtxt = "";
console.log(notesObj);
});
The issue is that you have the string 'null'
in your local storage.
Yes you compare with null
, but notes
is still JSON at this point, and apparently it can be null
encoded as JSON. So you'd also need to check for 'null'
as string.
Or, easier: Replace the whole if
with something like this:
const notesObj = (notes && JSON.parse(notes)) ?? []
If you want to be also resilient against invalid JSON in local storage, you can use this:
let notesObj
try {
notesObj = JSON.stringify(notes) ?? []
} catch(e) {}
to fix this issue use localstorage.clear() in the console. that's it.