javascriptlocal-storage

How to use localStorage to store data


I'm currently trying to learn how to use localStorage. I find myself in a loop while trying to add/update an array of users.

Here's the code:

const users = [
    {name: 'john', age: 25,},
    {name: 'jane', age: 25},
    {name: 'bob', age: 8}
]


const newUserInput = document.querySelector('#newuser');
const newAgeInput = document.querySelector('#newage');
const addUserBtn = document.querySelector("#addnewuser");

addUserBtn.addEventListener('click', (event)=>{
    event.preventDefault();

   
    users.push(createUser(newUserInput.value, parseInt(newAgeInput.value)));
    localStorage.setItem('users', JSON.stringify(users));
   
})

const createUser = (name, age) => {
    return {
        "name": name,
        "age": age
    };
    

}

So when i createUser for the first time, it worked and the updated users get stored into localStorage. But when i did it the second time, instead of adding another user, it only updates the first user that i added. Also, even if this works like I wanted to, I'm thinking I might run into a similar problem when I refresh the page, because now I'm redefining users with the original 3 members at the start again.

Any inputs would be very appreciated.


Solution

    1. Get existing items from local storage with the 'users' key. If it does not exist, then use the array of user objects that you made.

      let users = JSON.parse(localStorage.getItem('users')) || [
          {name: 'john', age: 25},
          {name: 'jane', age: 25},
          {name: 'bob', age: 8}
      ];
      
    2. Use let instead of const for users, this makes it mutable or modifiable rather than making it immutable or not modifiable.

    Hope these two steps help. TLDR: Change your const users into the code in step 1