Rather than overwriting it, append a new value to the localstorage

I am trying to insert the value of newUsername into the localStorage setUsernamesArray. However, my current code overwrites the existing value instead of adding to it.

Code

$('#signUpButton').click(function() {
  var newUsername = $('#usernameSignInBox').val();
  signedUpUsernames.push(newUsername);
  localStorage.setItem('setUsernamesArray', signedUpUsernames);
});

Answer №1

To update the array, remember that the data stored in localStorage is a string, not an array. To convert this string into an array and make updates, follow these steps:

  • Retrieve the string using
    localStorage.getItem('setUsernamesArray')
    ,
  • Convert the string into an array using JSON.parse,
  • Add new elements to the array,
  • Update the localStorage with the modified array using
    localStorage.setItem('setUsernamesArray', JSON.stringify(array))
    .

Answer №2

localStorage always saves data as a string, so make sure to convert your array into a string using stringify before storing it.

localStorage.setItem('usernamesArray', JSON.stringify(signedUpUsernames));

When retrieving the data, remember to parse it back into an array:

var retrievedArray = JSON.parse(localStorage.getItem("usernamesArray"))

Answer №3

localStorage.setItem function is used to replace the value of a key in the localStorage.

Think of localStorage as a variable. Just like when you reassign a variable,

var a = "Hello";
a = " World"

the value of a gets replaced. To prevent that, you can use +=

var a = "Hello";
a += " World"

Similarly, when working with localStorage, you need to create a new object with the updated value and then write it back to localStorage.

Here's an example:

function setValueToLS(key, prop, value){
  var _local = {};
  if(localStorage.getItem(key))
    _local = JSON.parse(localStorage.getItem(key));

  _local[prop] = value;

  localStorage.setItem(key, JSON.stringify(_local));
}

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

Ways to retrieve information from a $$state object

Everytime I try to access $scope.packgs, it shows as a $$state object instead of the array of objects that I'm expecting. When I console log the response, it displays the correct data. What am I doing wrong? This is my controller: routerApp.controll ...

How to identify the character encoding in a node.js request

Did you know that Facebook chat has a feature where it automatically detects and displays messages in a left-to-right format when typing in English, but switches to right-to-left style when adding right-to-left characters? I'm curious about how Faceb ...

The background appears only in the upper portion of the screen upon refreshing the table

Whenever the user clicks on the edit button or when the page is initially loading, a backdrop appears and disappears once the modal is displayed. The backdrop effectively highlights the entire page. However, after updating my table with data via Ajax witho ...

The Recharts Line chart fails to display newly added data points when data is updated

My app features a straightforward tool that enables users to monitor their weight changes over time. Despite successfully receiving new data in the props, the chart does not update and display the new point. Recharts Component: import React from 'rea ...

Navigating properties and linking information in React

I'm currently tackling a project that requires me to pass data to two distinct functional components. While my axios call to the API appears to be functioning properly, along with setting the state using hooks, I am continuously encountering two pers ...

Empty page displaying JSON output following form submission through AJAX

I'm attempting to implement an AJAX login feature on my web application. However, upon submitting the login form, I am faced with a blank page displaying JSON responses. For instance, upon successful login, I receive: {"success":true} When incorrect ...

Issues with Cross-origin resource sharing (CORS) arise when attempting to delete data using Angular

I am facing an issue with my Angular app (v1.13.15) and Express.js(v4.12.4) backend. Specifically, I have set up a DELETE method in my backend and enabled CORS support for it. However, every time I attempt to use the Angular $http.delete function, I enco ...

Changing a button's value on click using PhoneGap

I've been working with phonegap and came across an issue with my buttons setup like this: <input id="my_button" type="button" onclick="my_function();"/> The goal is to capture the click event and change the button's value, my_function ( ...

Incorporate visual elements such as images that resemble checkboxes

I'm searching for an innovative approach to replace the traditional checkbox, incorporating images instead. My idea is to have users click on an image, which will then fade out and reveal a tick box overlay. My inspiration comes from Recaptcha 2, whe ...

Implementing Sass mixin transition to specifically add transition-delay - a comprehensive guide

As I continue to enhance my front-end development skills and practice Sass to optimize my CSS code, I encountered a roadblock. After exploring resources and tutorials online, I created a global mixin in Sass named 'transition'. Here is the code: ...

When the ID and anchor link within a URL fail to scroll to the specified anchor location

I'm trying to add an id to a URL and scroll to an anchor link <a name="tags" id='tags'></a> <a href="edit.php?id=382#tags">GO</a> I have also attempted the following: <a href="edit.php?id=382&#tags">GO& ...

Tips for sharing data between two components

In my project, I have a customized Shared Component which consists of an input search bar with a "continue" button. This Shared Component is being utilized within two other components - the buy component and sell component. The challenge I am encountering ...

background with alternating stripes to decorate the border of a div

Is it possible to give a striped effect to a div element's border using jQuery? Consider the following code snippet: <style type="text/css"> #panel { padding: 50px text-align: center; background-color: #e5eecc; bord ...

Locate a piece of text with jQuery and enclose it within a specified container

Check out this code <form method="get" name="form_delivery"> Pick the country where you want your delivery<br> <select name="deliverymethod"> <option value="0" selected="selected">Choose a country / region</option> ...

Adding hyperlinks that do not redirect

I have 2 separate divs displayed on a website: <button class="form-control margin btn btn-warning hide_all" id="addLinks">Link Pages</button> <button style="display: none" class="form-control margin btn btn-primary hide_all" id="hideLinks"& ...

Navigation bar in HTML positioned on the right side of the webpage

My goal is to have a navigation bar on the right side of the page, taking up 250px, while allowing the main content to naturally adjust its size based on the window dimensions. I do want the main content to appear before the navigation in the HTML structur ...

Tips for creating a multitude of components

I have my react code in a single component and I am wondering how to split it into two components for the images container and showroom images. import React, { Component } from 'react'; export default class App extends Component { render() { ...

Are there any notifications triggered when a draggable element is taken out of a droppable zone?

Within a single droppable area, there is a collection of individual Field Names that can be dragged, and a table featuring X headers, each of which can be dropped into. Initially, these headers are empty. Is there a way to detect when an item is taken out ...

Exploring Best Practices for Coding in node.js

Method 1: Constructor and Prototype Objects function Database(url) { this.url = url; } Database.prototype.info = function (callback) { http.get(this.url + '/info', callback); }; Method 2: Closures Approach function Database(url) { ...

Is there a way for me to intercept JavaScript code before it runs on Chrome?

Looking to develop a Chrome extension for the developer tools that can intercept JavaScript code on a current web page prior to compilation or execution by the browser. I aim to instrument the JS code before it runs in the browser. Could someone assist wi ...