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.