Rick
Rick

Reputation: 57

Creating a favourites list using local storage

I'm trying to implement a favourites list that gets the id of the current game that the user is looking at. So far I have this:

$('#favouriteBtn').click(function(){
    currentAddFav();
});

function currentAddFav(){
    if(localStorage.getItem('favourites')){//If there are favourites
        var storage = JSON.parse(localStorage['favourites']);
        for (var i = 0;i <= storage.length;i++){
            if(storage[i] == currentGame.id){//Id already stored, we dont want a duplicate id so ignore
                console.log('id already stored');
                break;
            }
            else{//game id doesn't exist in storage so add the id to storage
                storage.push(currentGame.id);
                localStorage.setItem('favourites', JSON.stringify(storage));
                console.log('must be a new id?');
            }
        }
    }else{//No favourites in local storage, so add new
        var favArray= [];
        favArray.push(currentGame.id);
        localStorage.setItem("favourites", JSON.stringify(favArray));
        console.log('New favourites list');
    }

}

If I try adding a new favourite it works, if I try adding the same favourite that was first added to the list, it works fine. Then if I try adding a different favourite than the one first added, the array in local storage allows me to keep adding new ids to it.

Upvotes: 0

Views: 2258

Answers (1)

niklas
niklas

Reputation: 3011

Your loop is wrong

for (var i = 0;i <= storage.length;i++){

executes either the if or the else case for every item in the storage. What you would want is:

if (storage.indexOf(currentGame.id) == -1) { 
  # not found
  storage.push(currentGame.id);
  localStorage.setItem('favourites', JSON.stringify(storage));
} else {
  # found
  console.log('item already in favorites')
}

Upvotes: 1

Related Questions