• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

313
Vistas
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);
});
almost 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

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);
});
almost 3 years ago · Juan Pablo Isaza Denunciar

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) {} 
almost 3 years ago · Juan Pablo Isaza Denunciar

0

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

almost 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda