Search code examples
javascriptdexie

How do i get the id of a value i immidietly added using dexie js?


How do i access the id of an item i already added since the items are occasionally removed the incremented id is not uniform.

I have tried as in the documentation

    var db = new Dexie('FRIENDS');
    db.version(1).stores({
    friends: '++id,name,age,loves'
                });
    db.friends.add({
        name: 'user',
        age: 23,
        loves:'water',
    }).then(function(){
         return db.friends.get('user');
    }).then(function (res) {
        console.log(res.id);
    }).catch(function(error) {
             console.log ("Ooops: " + error);
          });

}

I get undifined


Solution

  • Correct answer is: created id will passed as argument in promise. Example from documentation:

    db.table('todos')
      .add(todo)
      .then((id) => {
        // ...
      });
    

    Or returned in async-await style:

    const id = await db.table('todo').add(todo);
    

    In your example you use wrong syntax of .get() method. Correct is:

    table.get({keyPath1: value1, keyPath2: value2, ...});
    // e.g.
    table.get({id: 15})
    // or
    db.friends.add({
            name: 'user',
            age: 23,
            loves:'water',
        }).then(function(id){
             return db.friends.get({id});
        })