skip to Main Content

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.

3

Answers


    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

    Login or Signup to reply.
  1. the users array is reinitialized with the original three members, and any previously added users stored in localStorage are ignored

     document.addEventListener('DOMContentLoaded', () => {
       let users = JSON.parse(localStorage.getItem('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();
    
          const newUser = createUser(newUserInput.value, parseInt(newAgeInput.value));
        users.push(newUser);
          localStorage.setItem('users', JSON.stringify(users));
    
          //-->Optionally, clear input fields after adding a user
         newUserInput.value = '';
         newAgeInput.value = '';
      });
    
      const createUser = (name, age) => {
          return {
             name: name,
             age: age
          };
       };
    });
    
    Login or Signup to reply.
  2. // Load users from localStorage or use default array
    let users = JSON.parse(localStorage.getItem('users')) || [
        {name: 'john', age: 25},
        {name: 'jane', age: 25},
        {name: 'bob', age: 8}
    ];
    
    // Function to create a new user object
    const createUser = (name, age) => ({ name, age });
    
    // Get DOM elements
    const newUserInput = document.querySelector('#newuser');
    const newAgeInput = document.querySelector('#newage');
    const addUserBtn = document.querySelector("#addnewuser");
    
    // Add event listener for the add user button
    addUserBtn.addEventListener('click', (event) => {
    event.preventDefault();
    
    // Create and add new user
    users.push(createUser(newUserInput.value, parseInt(newAgeInput.value)));
    
    // Save updated users array to localStorage
    localStorage.setItem('users', JSON.stringify(users));
    
    // Clear input fields
    newUserInput.value = '';
    newAgeInput.value = '';
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search