Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 497
Omidgh Avatar asked Mar 03 '23 18:03

Omidgh


1 Answers

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', []);
like image 181
Fraser Avatar answered Mar 27 '23 04:03

Fraser