Company logo
  • Jobs
  • Bootcamp
  • About Us
  • For professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
    • Bootcamp
  • For business
    • Home
    • Our process
    • Plans
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Calculator

0

195
Views
Why this code gives me "Uncaught TypeError: Cannot read properties of null (reading 'push')" error?

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);
});
7 months ago · Juan Pablo Isaza
3 answers
Answer question

0

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);
});
7 months ago · Juan Pablo Isaza Report

0

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) {} 
7 months ago · Juan Pablo Isaza Report

0

to fix this issue use localstorage.clear() in the console. that's it.

7 months ago · Juan Pablo Isaza Report
Answer question
Find remote jobs