Append to array in localForage
Asked Answered
J

1

13

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.

Jacobean answered 29/12, 2014 at 11:58 Comment(1)
I don’t think that is possible. But you could make a key system with keys like this key-1, key-2, and so on.Scalawag
F
7

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);   
Fab answered 24/8, 2018 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.