Omidgh
Omidgh

Reputation: 43

Local storage set Item replaces instead of update

I tried to save my data in local Storage with setItem but when I refresh the chrome tab and add data to my array, the data in localStorage delete the old data and set new data instead of updating that old data.

Here is my code:


let capacity = 200;
let reservedRooms = 0;
let users = [];

let rsBox = document.getElementById('reservebox');

class Reserver {
    constructor(name , lastName , nCode , rooms){
        this.name = name ;
        this.lastName = lastName ;
        this.nCode = nCode ;
        this.rooms = rooms ;
    }

    saveUser(){
        if(this.rooms > capacity){
            console.log('more than capacity');
        }else{
            users.push({
                name : this.name ,
                lastName : this.lastName ,
                id : this.nCode ,
                rooms : this.rooms
            });
            capacity -= this.rooms ;
            reservedRooms += this.rooms ;
        }
    }

    saveData(){
        localStorage.setItem('list',JSON.stringify(users));
    }



}


rsBox.addEventListener('submit',function(e){

    let rsName = document.getElementById('name').value;
    let rsLastName = document.getElementById('lastname').value;
    let rsNationalCode = Number(document.getElementById('nationalcode').value);
    let rooms = Number(document.getElementById('rooms').value);

    //Save the user data
    let sign = new Reserver(rsName , rsLastName , rsNationalCode , rooms);
    sign.saveUser();
    sign.saveData();





    e.preventDefault();
});

Upvotes: 4

Views: 1012

Answers (2)

Fraser
Fraser

Reputation: 17094

You are pushing an empty users array each time you reload the page, to resolve this you need to populate the users array from the items you have in storage.

e.g.

let users = [];

needs to be something like

let users = JSON.parse(localStorage.getItem('list')) || [];

The key point being that you need to load your existing users to be able to add to them, if you don't then you are essentially creating the users array fresh each time the page loads and you put data into it.

You may want to create something like a "loadData" function that checks if the array is initialized, loads it if it is and creates it if it isn't. You can make this generic so that you can use it to access any key and provide a default value if the key isn't present e.g.

function loadData(key, def) {
    var data = localStorage.getItem(key);
    return null == data ? def : JSON.parse(data)
} 

then

// load "list" - set to an empty array if the key isn't present
let users = loadData('list', []);

Upvotes: 6

darklightcode
darklightcode

Reputation: 2772

Another option would be to change the saveData method so you won't have to load the localStorage when the app is loading:

saveData(){
        let newList = JSON.parse(localStorage.getItem('list') || '[]')
        if(users.length) newList.push(users[users.length - 1]);
        localStorage.setItem('list',JSON.stringify(newList));
        newList=null;
}

Note: Be careful with localStorage because it doesn't have the same capacity on all browsers, you can check this post for more information

Upvotes: 1

Related Questions