Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Calculadora

0

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

0

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

7 months 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 empleo Planes Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2023 PeakU Inc. All Rights Reserved.