Discover the method for extracting multiple key values from an array stored in local storage

I am facing an issue with my sign-up form where I only need 2 out of the 6 input details to create a user object. Specifically, I require the username and password for a user to log in. However, I have encountered difficulties trying to extract only these two values from an object containing all 6 values stored in local storage. As a workaround, I created a separate array called 'userLogin' that holds just the necessary username and password values, which I then added to the local storage.

Now, when users try to log in using the provided form, I want to compare their input with the stored usernames and passwords. Unfortunately, when I check the console, it shows "ne," indicating a mismatch. I have tried various approaches and formulations to make it work but haven't found success yet. I suspect the problem lies in retrieving the correct items, although I'm not entirely certain. Your input on this matter would be greatly appreciated.

// Sign up page

const login       = document.querySelector(".login");
const loginSubmit = document.querySelector(".loginSubmit");

let users     = [];
let user      = {};
let userLogin = [];

signupForm.addEventListener("submit", (e) => {
  
  e.preventDefault();
  
  user = Object.fromEntries( [...document.querySelectorAll(".signup ul input")].map(e =>[e.name, e.value])); 

  users.push(user);
  userLogin.push(user.username);
  userLogin.push(user.password);

  localStorage.setItem('UserData', JSON.stringify(userLogin));
  console.log(localStorage);
});

// Log in page

const loginForm = document.querySelector(".login-form");

loginForm.addEventListener("submit", (e) => {
  let usernameInput = document.querySelector(".lg-username").value;
  let passwordInput = document.querySelector(".lg-password").value;
  e.preventDefault();
  if (localStorage.getItem("UserData")) {
    const dataUsername = JSON.parse(localStorage.getItem('UserData', 'username'));
    const dataPassword = JSON.parse(localStorage.getItem('UserData', 'password'));
    if(usernameInput === dataUsername && passwordInput === dataPassword) {
      console.log("ye");
    }else{
      console.log("ne");
    }
  }else{
    console.log("not regis");
  }

  console.log(localStorage)
});

html signup form:

<form class="join-form">
  <ul>
    <li><input type="text"     name="username" class="username" placeholder="Username"         required /></li>
    <li><input type="text"     name="fullname" class="fullname" placeholder="Full Name"        required /></li>
    <li><input type="email"    name="email"    class="email"    placeholder="Email Address"    required pattern=".+@gmail\.com"  /></li>
    <li><input type="text"     name="phone"    class="phone"    placeholder="Phone Number"     required /></li>
    <li><input type="text"     name="postcode" class="postcode" placeholder="Post Code"        required /></li>
    <li><input type="password" name="password" class="password" placeholder="Enter a password" required /></li>
  </ul>
  <input type="submit" class="signupSubmit"> 
</form>

html log in form:

<form class="login-form">
  <ul>
    <li><input type="text"     name="username" class="lg-username" placeholder="Username" required></li>
    <li><input type="password" name="password" class="lg-password" placeholder="Password" required></li>
  </ul>
  <input type="submit" class="loginSubmit">
</form>

Answer №1

I was struggling to find the best approach, so instead of directly looking for an item in a list stored locally, I decided to search for a specific string in the local storage and compare it with the user inputs. Here's how:

// Register page; saves user input

const signUp = document.querySelector(".signUp");
const submitButton = document.querySelector(".submitButton");

let listOfUsers = [];
let newUser = {};
let userCredentials = [];

signUp.addEventListener("submit", (e) =>{
    
    e.preventDefault();
    
    newUser = Object.fromEntries( [...document.querySelectorAll(".register ul input")].map(e =>[e.name, e.value])); 

    listOfUsers.push(newUser);
    userCredentials.push(newUser.username);
    userCredentials.push(newUser.password);

    signUp.innerHTML = `Welcome aboard, ${newUser.fullName}!`;
    signUp.style.fontSize = '1.3rem';
    signUp.style.fontFamily = 'Segoe UI, Tahoma, Geneva, Verdana, sans-serif';
    signUp.style.textAlign = 'center';
    signUp.style.marginTop = '55%'; 
    signUp.style.fontWeight = 'bold';
    
    localStorage.setItem('UserDetails', JSON.stringify(userCredentials));
    console.log(localStorage);
});

// Log in page; validates user input against sign up records

const loginForm = document.querySelector(".login-form");

loginForm.addEventListener("submit", (e) => {
    let usernameInput = document.querySelector(".lg-username").value;
    let passwordInput = document.querySelector(".lg-password").value;
    let loginDetails = [];
    e.preventDefault();

    if (localStorage.getItem("UserDetails")) {
        loginDetails.push(usernameInput);
        loginDetails.push(passwordInput);

        const registeredUsers = JSON.parse(localStorage.getItem('UserDetails'));
        if(registeredUsers.includes(usernameInput && passwordInput)) {
            console.log("Valid credentials");
        }else{
            console.log("Invalid credentials");
        }
    }else{
        console.log("Not yet registered");
    }
});

Answer №2

Great job! Your answer is very close to being correct.

Let's use this example for clarification:

sessionStorage.setItem('UserDetails', JSON.stringify(['example-username', 'example-pw']));

This code will store an array in sessionStorage with the key 'UserDetails'.

To retrieve these values, we can do the following:

const [user, pass] = JSON.parse(sessionStorage.getItem('UserDetails'));

Answer №3

while you were busy updating your content, I stumbled upon an old login code that I had.

const formLogin = document.forms['login-form']  // using the parent form to reference each form element

 ////    -----------  initialization section on page load.  -----------   -----------

formLogin.reset()  // reset formLogin to set initial values of elements to empty

const
  defaultLogin = JSON.stringify(Object.fromEntries(new FormData(formLogin).entries()))
, userLoggedIn = JSON.parse( localStorage.getItem('UserData') || defaultLogin )
  ;
Object.entries(userLoggedIn).forEach(([key,val])=>
  formLogin[key].value = val)          // setting user login form values from local storage

////   -----------   -----------   -----------   -----------   -----------
 
 
formLogin.onsubmit = evt =>
  {
  // getting user login values:
  Object.assign(userLoggedIn, Object.fromEntries(new FormData(formLogin).entries()) )
  // saving in local storage:
  localStorage.setItem('UserData', JSON.stringify(userLoggedIn))  

  // control part (only for testing) 
  console.clear() 
  console.log( formLogin.username.value, formLogin.user_psw.value  ) // accessing each element by its name
  console.log( JSON.stringify( userLoggedIn ) )

  evt.preventDefault(); // disabling page submit / and reload for testing purposes
  }

if you would like to test css + html

body {
  font-family : Arial, Helvetica, sans-serif;
  font-size   : 16px;
  }
fieldset {
  margin : 2rem auto;
  width  : 12rem;
  }
legend {
  font-weight   : bold;
  font-size     : 1.4rem;
  margin-bottom : .2rem;
  }
fieldset *:not(legend) {
  display    : block;
  float      : left;
  clear      : both;
  margin-top : 0.2rem;
  }
<fieldset label {
  margin-top : 0.8em;
  font-size  : .9rem;
  }
fieldset button {
  margin-top : 1.4rem;
  width      : 5.2rem;
  }
fieldset button:last-of-type {
  clear : none;
  float : right;
  }
<form name="login-form">
  <!-- have a name (or an id) here -->
  <fieldset>
    <legend> Login form </legend>

    <label>Name:</label>
    <input type="text" name="username" autocomplete="off"
            pattern="[A-Za-z0-9]{1,20}" placeholder="login name" 
            value="" required>

    <label>Password:</label>
    <input type="password" name="user_psw" 
            pattern="[A-Za-z0-9]{1,20}" placeholder="password" 
            value="">
<!--
    <label>4-digit PIN:</label>
    <input type="text" name="pinCode" autocomplete="off" 
          pattern="[0-9]{4}" placeholder="identification code"
          value="" required>
-->
    <button type="reset">clear</button>
    <button type="submit">Log In</button>
  </fieldset>
</form>

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 slider components have an endless loop feature that only runs once before coming to a

I'm working on creating an infinite slider that loops continuously without the need for navigation buttons. Instead, I plan to allow users to control the slider using touch gestures (although this functionality is not yet implemented in the code snipp ...

Assign the value of an element in an array to a variable using jQuery

https://i.sstatic.net/RtzeT.png In the jQuery variable, I have received an array and now I am looking to store each array value in a different variable. For example, I want to store the Address field in one variable. How can I achieve this? Any suggestion ...

How to pass arguments to page.evaluate (puppeteer) within pkg compiled applications

When I run my puppeteer script directly with node, everything works fine. However, once I compile the source using pkg, the page.evaluate and page.waitForFunction functions start failing with a SyntaxError: Unexpected identifier error. The specific code ...

Flexible structure PHP API that supports requests and responses in JSON or XML format

I am currently in the process of developing a PHP API (web service) that will primarily involve retrieving lists of items. These items may have sub-objects with their own fields, or even nested objects. Since this API will be utilized by various projects, ...

Step-by-step guide for integrating Attribute-Based Access Control (ABAC) in PHP

I recently discovered a framework by AT&T for developing ABAC. This particular framework utilizes XACML in XML format to construct rules, but it is only compatible with Java. However, I work with PHP and prefer to write rules in JSON format. Is my a ...

Utilize JavaScript associative arrays to dynamically populate a dropdown menu, followed by automatically filling in a text

As a newcomer to Javascript (although I have a strong grasp of php), I'm experimenting with using associative arrays to accomplish two tasks. The first task is successfully populating a dropdown menu: var select = document.getElementById('FName ...

Enhancing OpenAI API Responses with WebSocket Streaming through Express Middleware Integration

  Currently, I am in the process of developing an Express.js application that requires integration of OpenAI's streaming API responses to be transmitted in real-time to a front-end via WebSockets. Even though I have established communication between ...

Intersection of Integer Sets

Presented below is a code snippet that generates Integer Sets. Although everything seems to be functioning correctly, the issue lies within my intersectionWith function. Below is the IntSet code: public class IntSet{ private final int MAXALLOWEDSETVA ...

There was a TypeError encountered when attempting to read the length property of a null value in the Google Map JSON data

I keep getting an Uncaught TypeError: Cannot read property 'length' of null error when I attempt to use JSON data as markers on my Google map. However, when I check console.log(data);, it shows that the data is fine. What could be causing this is ...

What is the best way for ensuring that the test only proceeds after useEffect's update function has been executed?

function CustomApp() { let [counter, setCounter] = useState(0); useEffect(() => { setCounter(1); }, []); //<-------------------------set a checkpoint here to debug, triggered only once return counter; } // trouble-shooting ...

Is it possible to install non-root dependencies in node_modules using NPM?

The repository @superflycss/component-navbox contains the following list of dependencies: "devDependencies": { "@superflycss/component-body": "^1.0.1", "@superflycss/component-display": "^1.0.2", "@superflycss/component-header" ...

I recently discovered that in C/C++, when dealing with an array a, it is fascinating that (void*)&a is equivalent to (void*)a. How exactly does this

Throughout my experience, I've understood that in C/C++, when passing around an array named "objects," it actually contains the address of the first object in the array. I'm puzzled by how the pointer to the array "object" and its contained valu ...

How can Ext JS 4 handle the transmission of multiple metaData to support multiple dynamic grids by utilizing a single JSON file?

Looking to create multiple grids on a single panel using an accordion layout? I'll be dynamically generating all the grids based on metaData in JSON and handling metachange listener events on my store to reconfigure the grid. But here's the quest ...

suggestions for organizing data in an AJAX/jQuery page

Welcome to my JavaScript/Ajax webpage that also utilizes jQuery. I am facing a challenge with displaying a nested structure. Once a top level element is displayed, users should be able to click on it and reveal the levels below (which are dynamically gene ...

Creating an array from a CSV string: A step-by-step guide

To convert a CSV variable into an array, I am using the following code: $csv="one,two,tree,four"; $bits = explode(',',$csv); $elements = array(); for ($i=0;$i<count($bits);$i++) { $item .= '"'.$bits[$i].'"=>"'.$b ...

Define a property within an object literal that sets a function's property

I am defining a new tasks object: var tasks = { test: () => { /// .... } }; Within the test function, I am attempting to assign a value to the tasks.test.description property. Despite my efforts, such as: var tasks = { test: () ...

What is the methodology for analyzing connections resembling a tree structure?

I am in the process of creating a one-dimensional array to illustrate a specific number of objects. These objects are structured as depicted in the image: View Image My goal is to identify which object is connected to each other within this setup, with on ...

Troubleshooting problem with Materialize CSS in UI router

Incorporating Materialize CSS along with Angular's ui.router for state management and HTML rendering has led to a challenge. Specifically, the Materialize Select component is not initialized upon state changes since Materialize components are typicall ...

Retrieve elements from a numpy array using a separate array containing only 0 and 1 values as indices

If you have an index array called idx that contains only 0s and 1s where 1s represent the sample indices of interest, along with a sample array called A (A.shape[0] = idx.shape[0]), the goal is to extract a subset of samples based on the index vector. In ...

Can you explain the concept of the "node module wrapper function" in the context of Node.js?

Can someone explain to me the concept of a "module wrapper function" and how it affects my code? (function (exports, require, module, __filename, __dirname) { }); ...