user3419780
user3419780

Reputation: 1

updating a single value in localstorage

So i've got this piece of code to update the date and time a person leaves in localstorage

$scope.visitorout = function(){
var dateout1 = new Date(); 
var signout = JSON.parse(localStorage["allVisitors"]);
for(var i=0;i<signout.length;i++)
if (signout[i].id===signout[i].id) signout[i].dateout = dateout1;
localStorage["allVisitors"] = JSON.stringify(signout);
}; 

but whenever i call the function, it changes all the values of dateout for every single thing in local storage but i only want it to change just one

I have modified the code to this:

$scope.visitorOut = function(id){
var allVisitors = JSON.parse(localStorage["allVisitors"]);
var visitor;
for(var i=0; i<allVisitors.length; i++){
visitor = allVisitors[i];
if (allVisitors[i].id === visitor.id) {
visitor.dateout = new Date();
console.log(visitor.id)
break;
}
}
localStorage["allVisitors"] = JSON.stringify(allVisitors);

};

It updates the 'dateout' but for just the same item in localstorage and the console.log displays the same id each time...

<div class="list">
  <a class="item item-icon-left item-icon-right" ng-repeat="visit in visits | orderBy: '-date'" ng-click="visitorOut(id); closesignout()" ng-hide="visit.hide">
<i class="icon ion-person"></i>
{{visit.fname}} {{visit.lname}}
<i class="icon ion-log-out" ng-click="hideMe(visit)"></i>

Upvotes: 0

Views: 1372

Answers (2)

HankScorpio
HankScorpio

Reputation: 3651

This function needs to know which visitor to update. Wherever you're calling this function, you need to pass in at least the userId (if not the full user object) something like: $scope.visitorOut(user.id) or from html: <myElement ng-click="visitorOut(user.id)" />

$scope.visitorOut = function(userId){
    var allVisitors = JSON.parse(localStorage["allVisitors"]);
    var visitor;
    for(var i=0; i<allVisitors.length; i++){
        visitor = allVisitors[i];
        if (visitor.id === userId) {
            visitor.dateout = Date.now();
            break;
        }
    }
    localStorage["allVisitors"] = JSON.stringify(signout);
};

Note that I've used Date.now() here instead of new Date(). It's much easier to work with timestamps than Dates if you're going to stringify it. A timestamp can be converted to a Date like this:

var myDate = new Date(visitor.dateOut);

But if you want to convert a stringified date back to a Date object... it gets complicated (click).


I also changed the variable names a bit. Camelcase is a useful naming convention that aides readability, and from reading the rest of the code the signout variable seems to actually be an array of visitor objects, not an array of signouts, so I renamed that too.

Upvotes: 0

Travis Collins
Travis Collins

Reputation: 4020

This code looks like a bug. You are comparing an object to itself (which will always be true):

if (signout[i].id===signout[i].id)

Upvotes: 3

Related Questions