LocalStorage is designed to hold only the most recent data input

As I work on developing an app using PhoneGap for iOS, I encounter an issue with LocalStorage. After entering and storing a username and password on my iPad, I close the app, open it again, and enter a new set of login credentials. However, when inspecting the app using Safari Web inspector on my Macbook, I notice that only the most recent username and password are displayed under "Storage -> localStorage". The initial set of login data seems to have disappeared. Can anyone provide insight into why this behavior occurs?

Here is my JavaScript code:

<script type="text/javascript">
document.addEventListener("deviceready", onDeviceReady, false);

function onDeviceReady() {
    document.getElementById("btnSave").addEventListener("click", saveData, false);
    document.getElementById("btnGet").addEventListener("click", getData, false);
}

function saveData(){
    var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    window.localStorage.setItem("uname", username);
    window.localStorage.setItem("pass", password);
    alert("Your data has been saved");
}

function getData(){
    var output = "Your username is " + window.localStorage.getItem("uname") + " and your password is " + window.localStorage.getItem("pass");
    document.getElementById("result").innerHTML = output;
}
</script>

Here is the HTML code:

User Name: <input type ="text" id="username" /><br />
Password: <input type="text" id="password" /><br />
<button id="btnSave"> Save Data </button>
<button id="btnGet"> Get Data </button>
<div id="result"></div>

Despite my efforts to locate the missing stored data in the web inspector, I have been unable to identify the issue. Could there be a flaw in the code causing this unexpected behavior?

Answer №1

Here's a simple solution for storing user details:

var userArray = [];
var user1 = {name: "Alice", age: 25};
userArray.push(user1);
localStorage.setItem("users", JSON.stringify(userArray));
console.log(JSON.parse(localStorage.getItem("users")));

// Adding another user
var user2 = {name: "Bob", age: 30};
userArray.push(user2);
localStorage.setItem("users", JSON.stringify(userArray));
console.log(JSON.parse(localStorage.getItem("users")));

Each time you want to store user details, retrieve the existing data from local storage, add the new user details as an object to the array, and update the local storage with the updated array.

Answer №2

LocalStorage is a simple key-value storage system. When storing multiple values, you can implement a workaround as shown below:

const storedUsers = localStorage.getItem("users");
let users = [];

if(storedUsers === null){
  users = [];
} else {
  users = JSON.parse(storedUsers);
}

users.push("John");
//add a user

localStorage.setItem("users", JSON.stringify(users));
//update storedUsers with the new user data

Answer №3

Give this a shot

let data = [];
data = localStorage.getItem("userDetails");
let user1 = {userName : "firstUser", password : "password1"};
let dataArray = data.push(user1);
localStorage.setItem("userDetails", JSON.stringify(dataArray));
// Retrieving data
localStorage.getItem("userDetails");
console.log (JSON.parse(localStorage.getItem("userDetails")));

// Second attempt
data = localStorage.getItem("userDetails");
let user2 = {userName : "secondUser", password : "password2"};
dataArray = data.push(user2);
localStorage.setItem("userDetails", JSON.stringify(dataArray));
console.log (JSON.parse(localStorage.getItem("userDetails")));

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

Instructions on how to navigate back one page to determine which page initiated the action

I am looking for a solution to implement a back button that takes me back one page while caching it. Currently, I am using the following code: <a id="go-back" href="javascript:history.go(-1)" type="button" class="btn btn-danger">Back</a> Howe ...

Issue with JQuery Event Listener on Canvas Subelement not functioning

I encountered an issue while trying to implement a custom crop rectangle on a canvas using JavaScript. I created a function that, when called, should add a child node to the existing canvas and use JQuery listeners to draw the rectangle. However, although ...

Adjust the width of the element to match the size of the image within

My webpage features an image along with some accompanying metadata that I want to be centered on the page. I want the div holding the metadata to be the same width as the image. Here's an example: Unfortunately, I am unable to determine the image&apo ...

The navigation in Framework 7 is causing issues with the on-click functionality

Utilizing the framework's built-in formToJSON() function, I have been able to retrieve form values. By utilizing a click event, I am able to log the values. $$("#query-submit").on("click", function () { var queryForm = app.formToJSON("#query-form ...

Conceal varying numbers of rows in a table using Jquery based on specific

I am attempting to hide certain table rows, but I am encountering an issue. Currently, when I click on a row with the class 'plevel1', it hides the following row with the class 'plevel2'. However, when I click on the top parent level ro ...

Is there a way to work around the CORS policy in order to fetch data from URLs?

I have been developing a tool that can analyze URLs from an uploaded CSV file, search the text content of each URL, and calculate the total word count as well as the occurrences of "saas" or "software". The goal is to generate a new CSV file with the origi ...

On startup of the chrome app, read and load a JSON file into a variable

As I develop a chrome app, my goal is to store all configuration defaults in json file(s) alongside other assets. I am currently using AJAX requests to load them, but I'm wondering if there is a more efficient way to handle this. Is there perhaps an o ...

Revamping JSON structure by identifying id references

I recently attempted to update the city name within the JSON object provided below. "City":[ { "Name":"Delhi", "id":"c5d58bef-f1c2-4b7c-a6d7-f64df12321bd", "Towns":[ ...

Retrieve Gridview properties using JavaScript

I need to adjust the font size of my gridview using JavaScript to make it more suitable for printing. What is the best way to change the font size specifically for a gridview using JavaScript? ...

Converting a ReadStream to a ReadableStream in NodeJS: A Step-by-Step Guide

This question poses the opposite scenario to converting a ReadableStream into a ReadStream. ReadStream is a data structure utilized in Node.js ReadableStream is a structure that comes from the web platform, as detailed here As new runtimes like Deno or t ...

What is the best way to dynamically change the main content based on the sidebar option chosen in a React application?

https://i.sstatic.net/fkIyh.png Currently, I am in the process of creating the layout for the page similar to the image provided. When a user selects option A from the sidebar, my goal is to display the corresponding content on the same page without navig ...

Guide on dividing and presenting ajax information into two separate div containers

I am attempting to showcase two sets of data on separate divs using ajax. Below is the code I am utilizing for this task. Here is the ajax implementation $(function () { $(".myBtn").click(function () { var id = $(this).data("id"); ...

Locate and modify a specific element within an array of objects

Currently, I am working with an array that looks like this: arr = [{id:'first',name:'John'},{id:'fifth',name:'Kat'},{id:'eitghth',name:'Isa'}]. However, I need to add a condition to the array. If ...

Creating dual graphs simultaneously in Rickshaw

Can two graphs with different Y axes be plotted together? I have data on page views organized in a stacked area chart by referrer, and I would like to overlay a line graph depicting the number of actions over time. Although I already have both graphs ind ...

Authentication through Proxy and requests from nodes

I am attempting to make a get request to a website via https using the request module. However, I am behind a proxy that requires authentication. Despite my attempts to add the authentication, the connection to the site fails. I have experimented with add ...

Error Message: Execution Not Recognized and Missing Requirement

After going through numerous threads, I couldn't find a solution to my specific issue. It's quite unclear what I've installed or uninstalled, but I'm hoping that this error message and its details might provide some clarity. Even though ...

Issue with JQuery's parentsUntil method when using an element as a variable not producing the desired results

I'm having trouble with a specific coding issue that can be best illustrated through examples: For example, this code snippet works as expected: $(startContainer).parents().each(function(index, parentNode) { if (parentNode.isSameNode(commonConta ...

Send information to a different module

I've created a straightforward form component: <template> <div> <form @submit.prevent="addItem"> <input type="text" v-model="text"> <input type="hidden" v-model="id"> <i ...

"I am trying to figure out how to set a link to an image using JavaScript. Can someone help me

I need help figuring out how to insert an image or gif file within two inverted commas '' in this line of code: _("status").innerHTML = ''; (line number 13 in the actual code) Your assistance with this question would be greatly appreci ...

Utilizing Firebase authentication and next-auth in Next.js - Authentication currently returns null

I'm creating a website with nextjs 13 (app router) and incorporating firebase. I've come across suggestions to combine next-auth and firebase auth for using firebase auth effectively. Accordingly, I have configured my firebase Here is the fireba ...