简体   繁体   中英

Updating Local Storage

I have a struggle with updating Local Storage values. I have "users" array from which I want to update my Local Storage, buy many problems have occured durning implementation. Please see code below, and also take note its only learning so dont be scared I use local storage for stroing login and password.

class Register {
    constructor({
        inputLogin,
        inputPassword
    }) {
        this.inputLogin = inputLogin;
        this.inputPassword = inputPassword;
    }

    users = [];

    add() {

        const btn = document.querySelector('#register-form__submit');
        btn.addEventListener('click', (e) => {
            e.preventDefault();

            const usersData = {
                login: this.inputLogin.value,
                password: this.inputPassword.value
            }



            if (localStorage.getItem('users')) {

                   // // I dont know what to do here, I want to get existing value from local Storage. Put them back to array users and then set local storage with this old an new value... But I've encountered a lot of problems like nested arrays, overlooping etc. Please tell me guys how you would've done it.
            } else {
                this.users.push(usersData);
                localStorage.setItem('users', JSON.stringify(this.users));
            }

        })

    }

}

EDIT: Working solution. I hope it helps sombeody who wants to practice and doesn't know databases yet.

 class Register {
        constructor() {
    
            this.inputLogin = document.getElementById('login')
            this.inputPassword = document.getElementById('password')
            this.users = []
    
        }
    
    
        add() {
    //checking if inputs are empty
            if (this.inputLogin.value === '' || this.inputPassword.value === '') {
                this.alert('Musisz wypełnić wszystkie pola')
            } else {

//creating object with users data
                let userData = {
                    login: this.inputLogin.value,
                    password: this.inputPassword.value,
                }
    
    
                if (window.localStorage.getItem('users')) {

//checking if there are any users in local storage
                    const existingData = JSON.parse(window.localStorage.getItem('users'));
    
//looping through those values and checking if there is already such an user with this login.
                    for (let i = 0; i < existingData.length; i++) {
                        if (existingData[i].login === userData.login) {
                            if (document.querySelector('.red-alert')) {
                                return;
                            } else {
                                this.alert("user already exists");
                                break;
                            }
                        } else {
//checking if this.users[] is empty(this happens after refreshing page or restarting browser of course
                            if (this.users.length === 0) {
                                existingData.map((obj) => {
                                    return this.users.push(obj);
                                })
                                this.users.push(userData);
                                localStorage.setItem('users', JSON.stringify(this.users))
                                window.location.href = "index.html";
                            }
//checking if there is some data in this.users. That means page was not refreshed nor browser was restarted.

 else if (this.users.length > 0) {
                                this.users.push(userData);
                                localStorage.setItem('users', JSON.stringify(this.users))
                                console.log(this.users);
                                window.location.href = "index.html";
                            }
                        }
                    }
                }
 else {
                    //success when there are no users at all in this.users[] and local storage is empty
                    this.users.push(userData);
                    localStorage.setItem('users', JSON.stringify(this.users))
                    window.location.href = "index.html";
                }
            }

     alert(text) {
            const par = document.createElement('p')
            par.classList.add('red-alert');
            par.textContent = text;
            document.querySelector('.register-form').appendChild(par)
        }
    }

You need to first check for the existing key and then update the value of the local storage. Have added in line comments for better understanding

// ..rest of the code 

// check if the local storage have any key by this na,e
const currStoredData = localStorage.getItem('users');
// if key esxist
if (currStoredData) {
  // push the existing value of the key in the array
  this.users.push(currStoredData);
  // set the new user data in the local storage
  localStorage.setItem(usersData)

} else {
  this.users.push(usersData);
  localStorage.setItem('users', JSON.stringify(this.users));
}

})

You could read the local storage only at the beginning and work with the object after. Because the storage only saves strings, you need to parse the value as well.

class Register {
    constructor({
        inputLogin,
        inputPassword
    }) {
        this.inputLogin = inputLogin;
        this.inputPassword = inputPassword;
    }

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

    add() {

        const btn = document.querySelector('#register-form__submit');
        btn.addEventListener('click', (e) => {
            e.preventDefault();

            const usersData = {
                login: this.inputLogin.value,
                password: this.inputPassword.value
            }

            this.users.push(usersData);
            localStorage.setItem('users', JSON.stringify(this.users));
        })

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM