First, the "real class" example in the docs does not compile:
export class Contact implements IContact {
id: number;
first: string;
last: string;
emails: IEmailAddress[];
phones: IPhoneNumber[];
constructor(first: string, last: string, id?:number) {
this.first = first;
this.last = last;
if (id) this.id = id;
}
Compiler complains about id not being set in the constructor. Leaves the option to make id undefined
/id?
.
But with undefined id, Table.put()/add()
throws an error: Unhandled Rejection (DataError): Data provided to an operation does not meet requirements.
My example code:
export class DBProgram {
id?: number
name: string
description: string
constructor(name: string, description: string, id?:number) {
this.name = name
this.description = description
// if(id) this.id = id
}
save() {
return idb.transaction('rw', idb.dbPrograms, async () => {
// delete this.id
this.id = await idb.dbPrograms.add(this);
});
}
}
export class Idb extends Dexie {
dbPrograms: Table<DBProgram, number>
constructor () {
super("Idb")
this.version(1).stores({
dbPrograms: '++id, name, description, commands',
})
this.dbPrograms = this.table('dbPrograms')
this.dbPrograms.mapToClass(DBProgram)
}
}
export const idb = new Idb()
It runs and stores the object with auto id when I uncomment delete this.id
. But it seems that Dexie won't handle the undefined
id
.
Any hints on this?
Unfortunately it works in codesandbox: https://codesandbox.io/s/determined-lake-ntbzv?fontsize=14&hidenavigation=1&theme=dark
I don't know what's still wrong in my source compared to codesandbox. Maybe a version issue? The Dexie version is the same, though.
This issue is about difference in typescript since that Dexie example was written. Declare the id property as optional or with an exclamation mark to get around. I'll try to update the docs.
The runtime error is due to how ecmascript class fields proposal is set to handle class fields. This is also new but already implemented in chrome and when typescript transpiles to esnext it will let the class fields remain. A workaround for this exists in a PR that will come into next version of Dexie. It's not out yet though. The fix will probably go into version 3.0.4. I will leave a comment on this stackoverflow issue when it's available.