3

I'm using TaffyDB to have a local/offline database

but unfortunately - after refreshing the browser tab - it loses the data

example: I have this initial variable

var clist = TAFFY();

onclick event on button - it execute this statement

clist.insert({"123" , count:count , color:color , size:size});

after clicking it - and reload the browser tab , I execute this statement

alert(clist({PID : "123"}).count());//output 0

however the previous statement should output 1

AboMohsen
  • 109
  • 11

2 Answers2

3

but unfortunately - after refreshing the browser tab - it loses the data

Well, yeah, that's how TaffyDB works.

however the previous statement should output 1

No, it shouldn't.

TaffyDB is in-memory only. As soon as the context for your script is torn down, such as on a page reload, it's gone. If you want to persist it, you have to do that yourself.

The easiest thing to do is serialize the entire dataset as JSON and shove it in localstorage, provided it's small enough to fit there.

Brad
  • 159,648
  • 54
  • 349
  • 530
  • Thanks so much - can you tell me about another solution ? another database which saves the data locally/on JSON file – AboMohsen Apr 26 '18 at 15:20
  • I don't prefer any browser storage solution - as the user can clear caches and I loses it - I prefer to deal with JSON file – AboMohsen Apr 26 '18 at 15:24
  • 1
    The user can delete whatever they want, so what exactly did you have in mind? You can't just read/write arbitrary files to disk, and if you could, it could easily be deleted by the user just like browser cache. Are you saying you'd rather serialize your data as a blob, and prompt for download the file? Also, consider using CBOR if you don't need a text-compatible serialization format. – Brad Apr 26 '18 at 15:32
2

As per taffydb documentation, to persist data into localStorage, you can use db.store()

let db = TAFFY()
db.store('mydb')

This single function will both store the current data in-memory and retrieve previously stored data. So, if you call store at the beginning of your script, then on a window refresh, the stored data will be loaded.

BEWARE: However, the saving routine for db.store() is called as a non-blocking process... so if you wish to immediately retrieve data that you stored using some other call on localStorage, it will likely not be there. The best practice for store() is thus to call it on window load and then whenever you wish to save your existing data.

R J
  • 4,473
  • 2
  • 22
  • 29