Home > OS >  How to update existing localstorage items
How to update existing localstorage items

Time:03-14

I am building a small app, which at its current state allows to create a new user and login. When user is logged in, they can edit information about any user they select from a dropdown menu as seen in the screenshot: User panel

Here is the code:

//Gets info from localstorage
const select = document.getElementById("users-select");
const options = JSON.parse(localStorage.getItem('userdata'))

//for loop populates the dropdown by selecting usernames from localstorage
for (let i = 0; i < options.length; i  ) {
    let opt = options[i].username;

    let el = document.createElement("option");
    el.textContent = opt;
    el.value = opt;

    select.add(el);
}

//function fills out rest of the fields depending on selection of dropdown menu and is called in HTML by onchange attribute
function dropdownSelect() {
    const displayText = select.options[select.selectedIndex].text
    document.getElementById('usernameInput').value = displayText

    const userName = document.getElementById('usernameInput').value
    const userdata = options.find(user => user.username === userName)
    document.getElementById('passwordInput').value = userdata.password
    document.getElementById('idInput').value = userdata.id
    document.getElementById('emailInput').value = userdata.email
}

Now my issue is, how do I access the fields and update them? My initial idea was to reuse some code I have been using in registration part:

const usersCredentialsData = JSON.parse(localStorage.getItem('userdata')) || [];

function storeUsers() {
    registerUser({
        email: document.getElementById("signupEmail").value,
        password: document.getElementById("signupPassword").value,
        username: document.getElementById("signupUsername").value
    })
}

function registerUser(userData) {
  const randomId = Math.floor(Math.random() * 10000) * 1;
  usersCredentialsData.push({
    ...userData,
    id: randomId,
  });
  localStorage.setItem('userdata', JSON.stringify(usersCredentialsData));
}

However, at the moment I am a bit confused on how to proceed. Any tips and guidance will be greatly appreciated!

UPDATE:

I was able to break through a bit, however, the app adds a new entry in localStorage, instead of replacing it. Code snippet and screenshot bellow: New info

function storeupdatedUser() {
  registerUser({
      email: document.getElementById("emailInput").value,
      password: document.getElementById("passwordInput").value,
      username: document.getElementById("usernameInput").value,
      id: document.getElementById("idInput").value
  })
}

function registerUser(userData) {
  options.push({
  ...userData
});
localStorage.setItem('userdata', JSON.stringify(options));
}

In the screenshot, we can see that I tried to edit the ID of testuser3, however, it created a new entry in localStorage, with the same info, except the ID.

CodePudding user response:

If you want to reuse your code in registerUser, you need to pass the user id to your function

const usersCredentialsData = JSON.parse(localStorage.getItem('userdata')) || [];

function storeUsers() {
    registerUser({
        email: document.getElementById("signupEmail").value,
        password: document.getElementById("signupPassword").value,
        username: document.getElementById("signupUsername").value,
        id: document.getElementById('idInput').value //we need to pass user id here, even though it's null
    })
}

function registerUser(userData) {
  //find user index by user id
  const foundUserIndex = usersCredentialsData.findIndex(user => user.id === userData.id)

  //if found user index (we know this user added before)
  if(foundUserIndex) {
    //modify the existing user
    usersCredentialsData[foundUserIndex] = {
       ...usersCredentialsData[foundUserIndex],
       ...userData
    }
  } else { 
    //if no found user, just add a new user to the list (your original logic)
    const randomId = Math.floor(Math.random() * 10000) * 1;
    usersCredentialsData.push({
      ...userData,
      id: randomId,
    });
  }
  localStorage.setItem('userdata', JSON.stringify(usersCredentialsData));
}

BUT you need to keep in mind that you should not store user's password in local storage at all cost in a real application

If you save passwords in localstorage, anyone can see these passwords through that would not be safe!

CodePudding user response:

There's not update function for localStorage,Only can instead all of it.

if the storage have userdata then get it all,and change the infomation u want change and instead it.

if storage don't have,save it.

  • Related