taffyDB not save the data

1.5k views Asked by At

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

2

There are 2 answers

3
Brad On BEST ANSWER

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.

0
R J On

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.