Search code examples
angulardexie

Angular Dexie DB, updating Item


Updating an item logs correct, but old value persist

I'm trying to update the value of my Dexie Db however the old value persist.

This is from the parent component.

  async onEdited(tagItem: TagItem) {
    console.log("Id: " + tagItem.selection); // logs new value
    this.updateItem(tagItem);
  }

  async updateItem(tagItem: TagItem) {
    console.log("Id: " + tagItem.id); // logs correctly
    console.log("Id: " + tagItem.selection); // logs new value
    await db.TagItem.update(tagItem.id, {
      tags: tagItem.tags,
      Selection: tagItem.selection,
      isFlipped: tagItem.isFlipped,
    });
    // Get the updated item from the database
    const updatedItem = await db.TagItem.get(tagItem.id);
    console.log("Updated item: " + updatedItem?.selection); // logs old value
  }

I'm using the updateItem method in other functions as well, for updating other properties and then they update. But not in this function and I do not know why.

Let me know if I should post the templateUrl or other information. But since it logs correctly in the onEdited function, I really have no idea why this does not work.

I have tried skipping the async and await. Also tried with

setTimeout(() => {
      this.updateItem(TagItem);
    }, 500);

Solution

  • This seems very strange and I could not understand why you see this behavior. I don't know exactly what types selection, tags and isFlipped are but I assume tags is string[] and isFlipped is boolean.

    One theoretical reason for the issue would be in case selection would be a reference type such as an object or array and the value changes by some other code directly after having called updateItem(). To make sure this isnt' the issue, try if you get another result if you deep-clone tagItem in onEdited() before logging its value.

    async onEdited(tagItem: TagItem) {
        tagItem = JSON.parse(JSON.stringify(tagItem)); // (to surround the issue - don't keep this line) Just making sure we'll be working with an unchanged value
        console.log("Id: " + tagItem.selection); // logs new value
        this.updateItem(tagItem);
      }
    
    ...
    

    Other options to nail down the issue:

    1. Try using various versions of Dexie, such as 1.5.1, 2.0.5, 3.2.3 and 4.0.1-alpha.8. Are you seeing the same behavior on all versions?

    2. Are you seeing the same behavior on all browsers?

    3. Call db.TagItem.update() in a transaction and catch the result of the transaction - does the transaction commit or is any error being caught? You shouldn't need to do this - it's just me brainstorming ways to surround the issue.