4

I have defined an action for removing an item from an array:

export default class myStore {

  @observable items = [];
  ...
  ...

  @action deleteItem = async (target) => {
    try {
      await backendService.deleteItem(target.id);
      runInAction(() => {
        const targetIndex = this.items.indexOf(target);
        this.items.splice(targetIndex, 1);
      });
    } catch (error) {
      ...
    }
  };

  ...
  ...
}

Altough I made my component an observer, it still doesn't update my list until I trigger some other actions (click, rename, etc), in that case I will be able to see the item has been removed.

Am I missing something?

HTB
  • 413
  • 1
  • 9
  • 22
  • console.log(targetIndex); after const targetIndex = this.items.indexOf(target); – Jackkobec Sep 06 '19 at 19:52
  • @Jackkobec it gives me the correct index (e.g 3). If I refresh it manually or do some other actions it updates the list correctly. It's just not realtime (not observed) – HTB Sep 06 '19 at 19:56

1 Answers1

4

Try this solution:

@action deleteItem = async (target) => {
    try {
      await backendService.deleteItem(target.id);
      runInAction(() => {
        this.items = this.items.filter(item === target);
      });
    } catch (error) {
      ...
    }
  };
Jackkobec
  • 5,889
  • 34
  • 34
  • Thank you @Jackkobec, it worked! But I'm still wondering why it didn't work with splice? any ideas? also in terms of performance, which one is better? – HTB Sep 06 '19 at 20:45
  • Splice modifies the original array. Filter creates new from original filtered by predicate. The performance question is opened with understanding of the count of data. If this is a little array it makes no difference. – Jackkobec Sep 06 '19 at 20:49
  • 1
    my array length shouldn't be longer than 100. But do you know if there is a way (in mobx) to make it work with splice? the run time for splice is O(1) whereas for the filter it is O(n) – HTB Sep 06 '19 at 20:57
  • Algorithm complexity is different. But it is a funny data size. Of cause if items in array are not heavy. Try next with splice: this.items = this.items.splice(this.items.indexOf(target), 1); or this.items.splice(this.items.indexOf(target); return; – Jackkobec Sep 06 '19 at 21:02