Search code examples
javascriptreduxindexeddbdexie

ConstraintError: Key already exists in the object store


I am working with React 16.3.2, Redux 4 and Dexie 2.0.3.

when I am going to store data second time it throws this error message.

Error: ConstraintError: Key already exists in the object store.

   return dispatch => {
        db.table
        .add(data)
        .then (function(id){
            console.log(id)
        })
        .catch (function (error) {
            console.log("Error: " + error);
        });
    }

My Db schema:

   const db = new Dexie('ReactReduxDexieJsCRUD');
  db.version(1).stores({table:'++id,name,age,bloodGroup,donateBefore,weight' });

The first time it stores date well but after it gives the error.


Solution

  • How does your schema look like? (the part db.version(x).stores({...}) ?

    The most common is to have inbound primary key, example:

    db.version(1).stores({
      table: 'id, idx1, idx2...'
    });
    

    Here id is the primary key.

    • db.table.add({id: 1, foo: 'bar'}) will add object with id 1.
    • db.table.add({id: 1, foo: 'bar2'}) 2nd time will fail because id 1 exists.
    • db.table.put({id: 1, foo: 'bar2'}) will update object with id 1.

    So what do you really want to do? You say you want to add new object with new key. If so, I suppose the error is that you give the same key second time.

    You can also let the id be generated by the db

    db.version(2).stores({
      table: '++id, idx1, idx2...'
    });
    

    Then you don't need to supply id in calls to add():

    • db.table.add({foo: 'bar'}) will add object with id 1.
    • db.table.add({foo: 'barX'}) 2nd time will add new obj with id 2
    • ...