Error: HTMLButtonElement on notes-taking website unable to read property 'push' of null

I'm encountering an issue with this code that is resulting in an error message:

Uncaught TypeError: Cannot read property 'push' of null at HTMLButtonElement. (app.js:15)

console.log("Welcome to Notes Taking Website");

// To store notes in the local storage

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);
    localStorage.setItem("notes", JSON.stringify(notes));
    addTxt.value = "";
    console.log(notesObj);

})

Answer №1

The reason for this issue is that there is already data stored in your localStorage. When the code reaches the else statement, it tries to create a new array, resulting in an error being thrown.

To resolve this, you need to clear the localStorage first.

 localStorage.clear(); 

After clearing the localStorage, the code should work properly.

Answer №2

When attempting to use the JSON.parse() method on the variable 'notes', it was discovered that it does not return an array, therefore lacking a push method. It is possible that 'notes' is either an object or null. It is important to check the declaration of 'notesObj' and ensure that it is within the correct scope.

Answer №3

Start by clearing the localStorage:

     localStorage.clear();

Additionally, replace (notes) with (notesObj) in the following line:

      localStorage.setItem("notes", JSON.stringify(notesObj));

Executing these steps will ensure successful execution!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript Array Multiplication Theory

I am working with 2 arrays list1 = ["x","y"] list2 = [ ["5","6","7"],["20","21","22"]] My goal is to create an array of objects like this: [ {list1: x , list2: 5}, {list1: x , list2: 6}, {list1: x , list2: 7}, {list1: y , list2: 20}, {list1: y , l ...

Having trouble getting the finally clause to work properly in Angular JS version 1.7

In my current project, I am utilizing Angular JS 1.7. Recently, I encountered an issue while using the finally clause within a promise: $http.put( url, null, { headers: { 'Content-Type': 'application/json' } } ).then( ...

Issue with starting React app using the "npm start" command

Upon the installation of a React App, I encountered a error message after executing the command "npm start" Cannot destructure property compile of 'undefined' or 'null'. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href=" ...

Update the JSON data based on the specifications outlined in my project

class Transformation { constructor() { this.colHeaders = { error_description: "Description", error_status: "Status", error_code: "Error Code" }; } getColHeader() { return this.colHeaders; } } var jsonData = { error ...

establishing a "string" array within an array of structures and assigning it a value

Within my program, there is a struct that contains information such as name and age. The issue lies within the displayRecords() function in the main section where I am attempting to bubble sort an array of these structs based on age. While I have been succ ...

The variants array in VUE.js is not displaying properly

I have recently been delving into vue.js for my work and encountered a significant issue. I wanted to create a simple TODO application. In my index.html file, I only have a div for a header and a root div with an ID: #app. Inside the root div, there is a ...

Tips for Disabling ML5 Posenet

Looking to halt Posenet after completing app task private sketch(p: any) { p.setup = () => { this.poseNet = ml5.poseNet(p.createCapture(p.VIDEO), { outputStride: 8 }); this.poseNet.on(&apos ...

Use JavaScript and PHP to retrieve a value from an array and dynamically populate select options based on that value

In my PHP code, I have two arrays structured like this: Array ( [0] => 11 [1] => 11 [2] => 11 [3] => 11 [4] => 11 [5] => 187 ) Array ( [0] => 118 [1] => 112 [2] => 85 [3] => 81 [4] ...

The read more button is not functioning properly when used in conjunction with the <br>

Can someone help me debug an issue I'm facing with my code? I have created an HTML tab that contains multiple DOM elements, each with a "Read More" button. Everything works fine when it's just plain text, but as soon as I add tags within the p ...

Refresh State component following fetch using Redux

Greetings everyone, I'm currently in the process of learning React and Redux. I've encountered a challenge where I am unable to update the state of a specific container using Redux without resorting to a setTimeOut function due to the asynchronou ...

What is the ideal amount of data to store in browser cache?

I am facing the challenge of loading thousands of user data records from a REST service, specifically user contacts in a contact-management system, and conducting a search on them. Unfortunately, the existing search functionality provided by the REST servi ...

What is the best way to utilize multiple props within a single callback function declared in a template literal when using React styled-components?

I recently incorporated styled components into my React project, but I'm encountering difficulty using multiple props to define styles in my components. Here's the crux of the problem: const sizes = { lg: css` width: 200px; h ...

Allow the response to be returned in the parent function by using the $.post method

I have a question regarding this particular code snippet: null. Why is the server_request function not returning the responseText as expected? And how can I modify it to achieve the desired outcome?</p> ...

Exploring Navigation in AngularJS with ui-router

I've encountered an issue with ui-router functionality in my code. Here's a breakdown of the problem: Within my index.html file <li> <a ui-sref="day2">Day 2</a> </li> <li><a ui-sref="day3">Day 3</a& ...

Animating a gradient within an SVG element following along an SVG path

I successfully created an SVG egg and animated a path while adding a gradient, but I am facing an issue. The linear gradient goes from top to bottom, but I want the dark color at 0% and the light color at 100%. Essentially, I want the gradient to follow th ...

Click on the link to open it in a SharePoint modal and populate it with the value from the

After populating a ng-grid with SharePoint items, my goal is to have the SharePoint edit form open in a modal window when the edit button at the end of each row is clicked. However, I am encountering difficulties when using OpenPopUpPage as the {{row.entit ...

Determining the variance in object elements when the key is not consistently present

In my array of objects ($data['messages']), I need to calculate the mileage difference. For example, in the data below, the mileage difference is 200 km (5200-5000). The challenge is that the key may not always exist. What is the most efficient ...

Explore Marker GeoCharts within AngularJS to enhance visualization capabilities

I am trying to customize the markers on a GeoChart similar to the one shown in this example. Could you please guide me on how to add the mapsApiKey in Google GeoChart using the ng-google-chart directive? Here's an example code snippet: var chart = {} ...

Retrieve the element's value in relation to a different parent element

[JavaScript] How can I access the value of a textbox related to a button through jQuery? The event is triggered when the .button-action is clicked <td class="dmsInput"> <input type="text" maxlength="4" size="4" class="d"> </td> <td& ...

Styling of global checkbox focus in Material UI (applied globally, not locally)

Currently experimenting with customizing the styling of a checkbox when it is in focus globally using Material-UI (react). At present, only default and hover styles are taking effect: MuiCheckbox: { colorSecondary: { color: 'green', & ...