Zaccheus Wilson
Zaccheus Wilson

Reputation: 29

Im trying to create an array of user Objects in local Storage using vanilla JS

I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead

//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);
        


    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))


}

storeUsers(newUser);

Upvotes: 0

Views: 242

Answers (3)

ikhvjs
ikhvjs

Reputation: 5957

You miss quotes in localStorage.getItem.

I also recommend you separate the functionality of your function like below:

class UserScoreTemplate {
    constructor(userName, userScore) {
        this.user = userName;
        this.score = userScore;
    }
}

function storeUsers(userObject) {
    let users = [];

    if (localStorage.getItem("users")) {
        users = JSON.parse(localStorage.getItem("users"));
    }

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users));
}

const newUser = new UserScoreTemplate("John", "Doe");

storeUsers(newUser);

Upvotes: 1

sid
sid

Reputation: 2027

Correct reference should solve it, the arguments passed to function(usersName, usersScore) will not be accessible outside the function, thats why your code doesn't work. You're passing parameter to the storeUsers function so that should be used whereever needed.

newUser = new userScoreTemplate(userObject.userName, userObject.score);

Upvotes: 1

Tom
Tom

Reputation: 5667

You are missing quotes around users :

if (localStorage.getItem("users") === null) {

Upvotes: 1

Related Questions