Issue with the browser's local storage functionality not functioning as expected

For some reason, I am facing an issue with using browser local storage to store an array. When testing it out, both indexes of the array are returning "null". Can someone help me identify what's going wrong?

window.localStorage.clear();
var requesterID = "ABC";
var title = "title";

if (window.localStorage.getItem("alreadyGotLastForAWeek") == null) {
    window.localStorage.setItem("alreadyGotLastForAWeek", JSON.stringify(["placeHolder1"]));
}

window.localStorage.setItem("alreadyGotLastForAWeek", JSON.stringify(JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek")).push(requesterID+title)));
var tempArray = JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek"));

console.log(tempArray[0]);
console.log(tempArray[1]);

Expected Result:

placeHolder1
ABCtitle

Actual Result:

null
null

Answer №1

The reason for this behavior is that when Array.prototype.push is used, it not only adds the element to the array but also returns the new length of the array, as explained in detail here.

To address this issue, one option is to divide your function into separate steps:

const array = JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek"));
array.push(requesterID+title);
const stringifiedArray = JSON.stringify(array);

window.localStorage.setItem("alreadyGotLastForAWeek", stringifiedArray);

Alternatively, you can utilize Array.prototype.concat instead of push:

window.localStorage.setItem("alreadyGotLastForAWeek", JSON.stringify(JSON.parse(window.localStorage.getItem("alreadyGotLastForAWeek")).concat([requesterID+title])));

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

What is the best way to handle and fix incorrect characters?

I have a JavaScript code snippet that is designed to check for invalid characters in a string. The only allowed characters are a-z, A-Z, 0-9, and -: var str = 'Some string!', invalid_characters = []; if (/^[a-zA-Z0-9-]*$/.test(str) == false ...

Scrolling and hovering now triggers the fixed button to toggle class seamlessly

Currently, I am attempting to modify the class of a button on my website. The initial state of the button is wide, but as the user scrolls, it should shrink in size. When hovering over the shrunken button, it should expand back to its original width. Alt ...

The Ionic project compilation was unsuccessful

Issue: This module is defined using 'export =', and can only be utilized with a default import if the 'allowSyntheticDefaultImports' flag is enabled. Error found in the file: 1 import FormData from "form-data"; ~~~~~~~~ node ...

Issues with Cordova and JQuery ajax functionality not operating as expected

I am facing an issue with implementing AJAX functionality in my Cordova app (CLI 6.3.1) on Visual Studio 2017. It works fine on the emulator, but I encounter a connection error when installing it on a mobile phone. I have already included CSP as shown bel ...

Create a std::array<T, N> with a large N=256 value for a complex type

Does anyone have a solution for populating an std::array<T, N> with T being a non-default-constructible struct/class and N known at compile time but too large to hard-code each element individually (e.g., N=256)? The constructor in my case takes one ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...

Is it possible to utilize the array_filter() function on an array of class objects?

Currently, I am working on intercepting and filtering items from a class set array called $this->_vars in a simplified version of Smarty (not by choice :| ) Below is the code snippet that I have been using: Class Callback Function private function ca ...

Changing char array values to hexadecimal in C (for example: {'5', 'A'} becomes 0x5A)

I have a task to convert the contents of stringList into hexadecimal format within the scope of the function MyFunction. This is necessary because the function WriteI2C requires a hex value as input. For instance, if the stringList contains '5' a ...

Revive your Chart JS visualization with interactive re-animation via onclick action!

I've been exploring Chart.js and trying to achieve something simple, but I'm having trouble. I just want the chart to re-animate when clicking on a button, but I can't seem to make it work. I attempted to attach chart.update to the onclick e ...

Toggle between bold and original font styles with Javascript buttons

I am looking to create a button that toggles the text in a text area between bold and its previous state. This button should be able to switch back and forth with one click. function toggleTextBold() { var isBold = false; if (isBold) { // Code t ...

Traverse through a pair of arrays, iterating over one array in a loop until the second array reaches its end (for example, setting colors for menu navigation items

Hey there! I'm facing a challenge in my code. I have two arrays - one for menu navigation items and another for colors: $nav_items = array('item1_link'=>'item1_displayname', 'item2_link'=> ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

Difficulty in accurately retrieving the value in a PHP echo statement using jQuery

$id = "123"; When on the page book.php, $id is passed to an external jquery-book.php file. <script type="text/javascript"> var id = '<?php echo $id; ?>'; </script> <script type="text/javascript" src="jquery-book.php"& ...

I received incorrect JSON data

Take a look at my PHP code for encoding JSON data from MySQL database. Check out the URL . I validated the JSON data using JSONLint, which showed it as valid. However, instead of receiving the data in JSON format, I got the result [false]. Can anyone hel ...

provide an element reference as an argument to a directive

I am trying to figure out how to pass an element reference to a directive. I know that I can get the reference of the element where the directive is applied using private _elemRef: ElementRef but my goal is to pass the reference of another element to the ...

Updating React state via child components

Encountering a strange issue while working on a project, I managed to replicate it in this jsfiddle. The parent component's state seems to be affected when the child component updates its state. Any insights on what might be causing this? Here is the ...

Troubleshooting issue with JQuery AJAX loading Bootstrap Dropdowns

I have a website on GitHub Pages that uses Bootstrap, but I'm having issues with the drop-down menu in the navbar. Sometimes it works and sometimes it doesn't. I am using $("#nav").load("url"); to load the navbar so that I can make changes and ha ...

Extracting the inner content in the absence of an HTML element, only plain text

My website's platform has some unusual HTML that I need to work with. There is a section of code that looks like this: <div class="report-description-text"> <h5>Description</h5> Welcome to Ushahidi. Please replace this report with a ...

Shift the sleek navigation arrows to the interior of the slides

Is there a way to relocate the navigation arrows on the slider images? I have tried various methods found online with no success. Currently using ASP.NET, but doubt it matters. Employing the latest version of SLICK. Here is the HTML code snippet: <%@ ...

In JavaScript, the elements within document.forms[0] are distinct from those within document.<formname>

In my attempt to incorporate client-side validation in Struts 2 with the xhtml theme, I have encountered an issue. The JavaScript being generated is unable to validate my code. Upon further investigation, I discovered that Struts is using a specific notati ...