Storing items in localStorage

I have a unique need for saving passwords in localStorage, so please don't try to figure out the reason behind it. I simply want to know if it can be done.

Here's the scenario: I have a registration form. If the localStorage is empty, I save an object in it. If there is already an object stored in localStorage, I retrieve it, push it into an array, and then add the new object to this array. Finally, I set this updated array back in localStorage.

const registrationForm = document.getElementById('registration');
   registrationForm.addEventListener('submit', e => {
      e.preventDefault();
      let regName = document.querySelector(".registration__name").value;
      let regPassword = document.querySelector(".registration__password").value;
      let regEmail = document.querySelector(".registration__email").value;
      let clientObj = {
         name : regName,
         password: regPassword,
         email: regEmail
      };
      let clientsArr = [];
      clientsArr = JSON.parse(localStorage.getItem('Users'));
      if(!clientsArr) {
         localStorage.setItem('Users', JSON.stringify(clientObj));
      } else {
         clientsArr.push(clientObj);
         localStorage.setItem('Users', JSON.stringify(clientsArr));
      }
   })

Is this approach feasible? With this code, am I creating a new array each time and pushing objects endlessly?

Answer №1

Check out the code snippet below

const registrationForm = document.getElementById('registration');
   registrationForm.addEventListener('submit', e => {
      e.preventDefault();
      let regName = document.querySelector(".registration__name").value;
      let regPassword = document.querySelector(".registration__password").value;
      let regEmail = document.querySelector(".registration__email").value;
      let clientObj = {
         name : regName,
         password: regPassword,
         email: regEmail
      };
      let clientsArr = [];
      if(!localStorage.getItem('Users')) {
         clientsArr.push(clientObj);
         localStorage.setItem('Users', JSON.stringify(clientsArr));
      } else {
         clientsArr = JSON.parse(localStorage.getItem('Users'));
         clientsArr.push(clientObj);
         localStorage.setItem('Users', JSON.stringify(clientsArr));
      }
   })

Answer №2

It is important to ensure that localStorage is set to an array for proper data storage:

   const usersArray = JSON.parse(localStorage.getItem('users')) || [];
   usersArray.push(newUser);
   localStorage.setItem('users', JSON.stringify(usersArray));

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

The visibility in the viewport is always showing as visible for all elements upon loading

Seeking advice from fellow developers! I'm encountering an issue with my code meant to detect when items are in the viewport. Strangely, the first .each loop is returning 'visible' for every item, even though it's not triggered by scrol ...

Trigger a warning pop-up if a selection has not been made in a dropdown menu using jQuery

I am attempting to display an alert popup when the user fails to select a value from the dropdown menu. Below is my HTML code: <div id="reminder" class="popup-layout"> ... ... </form> </div> In my JavaScript function page, I have tried ...

The Google analytics page tracking feature is experiencing issues within an AngularJS application and is not functioning correctly

My current project focuses on AngularJS, catering to both mobile applications and desktop websites. I have downloaded analytics.js locally and integrated it into my GA tracking code within the index.html file: (function(i,s,o,g,r,a,m){i['GoogleAnalyt ...

Untangling REGEX URLs for Effective Filtering

I am currently working on creating a filter for a video list. I have successfully put together a string that includes all the values selected by the user for filtering. Right now, I am passing this string as a parameter through the URL. For example: NOTE ...

Tips for transporting an npm module to a different file without reliance on the require function in that specific file

I am curious about how to export the npm module to another file without utilizing the required function in that file. -index.js- const cv = require("opencv4nodejs"); const add = require("./addon"); cv.imshowWait("", add.img( ...

What is the best way to condense all JavaScript and CSS files in MEAN.JS for a production setting?

I recently finished creating a basic MEAN.JS application. When using MEAN.JS, I can use the command grunt build to minify the js and css files located in specific folders: css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config ...

When clicking initially, the default input value in an Angular 2 form does not get set

I am currently learning angular2 as a beginner programmer. My goal is to create a form where, upon clicking on an employee, an editable form will appear with the employee's current data. However, I have encountered an issue where clicking on a user f ...

Identifying memory leaks caused by rxjs in Angular applications

Is there a specific tool or technique available to identify observables and subscriptions that have been left behind or are still active? I recently encountered a significant memory leak caused by components not being unsubscribed properly. I came across ...

Creating dynamic bootstrap carousels with the power of jquery and javascript

I need assistance with creating a website using only html, js, and bootstrap. The issue I am facing involves implementing multiple carousels dynamically onload. Below is an example of the girls_ethnic data set. Similarly, I have boys_shirts, boys_pants, ...

What are some ways to streamline a conditional expression in v-bind?

What is a way to streamline the conditional expression in v-bind? :href="type === 'exampleType'?`${link}/${id}?exampleGetParam=true`:`${link}/${id}`" without duplicating ${link}/${id} ...

Use radio buttons to enable switching between different data options within a dropdown menu

I am working on a dropdown box that is populated dynamically using JSON data. The content in the dropdown can be categorized into 4 types, so I have included radio buttons to switch between these categories. I have created HTML code to toggle between manu ...

Exploring the Implementation of Box Icons in a Vuejs For Loop

I am currently exploring the box icons web component and I am trying to integrate the icons into my link array for each item. However, I am uncertain about the best approach to achieve this. <div class="container"> <div class="l ...

Storing arrays within core data

I am in the process of developing an application that involves gathering user input and storing it in an array for future use. The user input has been saved under the variable numToEnter. Here is a snippet of my code: var nums = [NSManagedObject]() ...

Obtaining the contents of a local directory with JavaScript

Currently, I am attempting to access the contents of a local folder using JavaScript. Despite my efforts with the Filesystem API, an error is consistently appearing: DOMException: It was determined that certain files are unsafe for access within a Web app ...

Display the output based on checkbox selection using JavaScript

I am working on a feature where I need to capture checkbox inputs using JavaScript and then store them in a PHP database. Each checkbox corresponds to a specific column in the database. If a checkbox is checked, I want to insert its value into the databa ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Is there a way to dynamically count the length of an element or class in realtime using JavaScript?

If there are currently 5 divs with the class name "item" and a new unknown number of divs with the same class name "item" are dynamically added in real time, I want my result to display the total number of divs present at that moment (i.e., 5 + n). Note: ...

The vital role of Package.json in the distribution of packaged products

I am currently uncertain about the purpose of package.json in relation to packaging. My understanding is that dependencies listed under dependencies will be included in the distribution package, while those under devDependencies will not be included. How ...

Retrieve JSON data using Google Chrome

I am encountering difficulties in fetching data from a local json file on my machine. Despite trying various solutions I found, I have been unsuccessful... Here is the code snippet I have used: When attempting to fetch the API, I encountered the error me ...

Versatile Function for Handling Dropdown Changes

I am faced with the challenge of executing a javascript function when multiple select elements are changed. I want to create a versatile function that can be set as the onchange method for various select elements. The following code accomplishes this task ...