auth0/angular-storage

localstorage value gets updated without using the store.set() method

Closed this issue · 2 comments

Hi,
Thank you for this awesome storage package. I have been using this in many ways and in many projects.

Today while using store I found a bug. The issue is, first I set a JSON using store.set('objectName',myObject);.
And when I need it I fetch that object using store.get('objectName'), and once I get this object I set a new property in this object, but while doing this the store('objectName') gets updated from localstorage automatically with that new property.

Example:

angular
.controller('myCtrl', function(store){
var myObject = {
'value_1': 'value 1',
'value_2': 'value 2'
};
store.set('objectName', myObject);
})
.controller('newCtrl', function (){
var newObject = store.get('objectName');
newObject.value_3 = 'value 3';
console.log(store.get('objectName'));
});

above console.log gives you below result
{
'value_1': 'value 1',
'value_2': 'value 2',
'value_3': 'value 3'
}

Can anyone help me with this?

Hi,

I hope it's not too late for a response.

This situation you're describing is not a bug in angular-storage. In fact is the way that javascript works.

Javascript pass objects by reference (kind of). When you retrieve the object from store in the second controller Javascript detect that the object is the same (with the same fields and values) and "bind" them to be more efficient.

Let's review this post http://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language.

My advise: if you have this situation and you want to keep them isolated you should clone the object your'e retrieving from the storage.

Here you can see an example using underscorejs to clone the object:
https://embed.plnkr.co/yf4XOGeZaB4ieyr4DViM/

@miguelchico Thanks for the reply. I have used angular.copy();.