Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Append to array in localForage

I am using localForage to store some data on a website to make it offline.

I would like to have one key and append to the value / array.

So far I can only figure how to retrieve the entire key/value from storage, then append and set the entire key/value again. This seems very wasteful and might be problematic when the key/value gets larger.

var obj = ...
localforage.getItem('documents', function(err, value) {
  value.push(obj);
  localforage.setItem('documents', value);
}

Is there not a more efficient way of doing this? and how big would the key/value have to be to notice performance issues.

like image 621
Karl Stulik Avatar asked Dec 29 '14 11:12

Karl Stulik


1 Answers

I realize this is an old question, but thought I would provide some info. Per NatureShade's point, you can't edit the value in the localForage table, you can only pull the item, and set it. What I typically do for frequently changing variables/objects when using localForage is to have a global variable set for that item. When making changes I just update the global variable and then update the item in storage. The nice thing about this is you only have to worry about setting the localForage key/value, and don't have to mess with the asynchronous aspect as much. You also have a variable that you can always reference for this info as well, so you don't have to use .getItem all the time to access it. Having a global variable may not be the best practice, but it is an option.

var globalObject;
localforage.getItem('documents', function(err, value){
    globalObject = value;
}

var obj = ...;
globalObject.push(obj);
localforage.setItem('documents', globalObject);

var obj2 = ...;
globalObject.push(obj2);    
localforage.setItem('documents', globalObject);   
like image 164
Jacobalo Avatar answered Nov 10 '22 13:11

Jacobalo