Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MobX computed runs before item is actually inserted into array

I'm using React in combination with MobX. I use a store with an observable array (conversations) and would like to offer a sorted version of this array as a computed property. When adding a new conversation, the computed property sortedConversations is evaluated before the conversation is added to the array. In the small example below, 'Reordering conversations' is always logged before 'Added conversation'. Am I doing something wrong?

class Store {

    ...

    @observable conversations = [];

    addConversation(conversation) {
      this.conversations.push(conversation);
      console.log('Added conversation');
    }

    @computed
    get sortedConversations() {
      console.log('Reordering conversations');
      return _.orderBy(this.conversations.slice(), ['lastUpdated'], ['asc']);
    }
}
like image 386
Basti Avatar asked May 20 '26 09:05

Basti


1 Answers

You are not doing anything wrong. The MobX API looks like regular JavaScript, but every time an observable is updated, all its observers are updated synchronously under the hood. This will not be an issue in this case, but you could wrap the contents of addConversation in a transaction:

addConversation(conversation) {
  transaction(() => {
    this.conversations.push(conversation);
    console.log('Added conversation');
  });
}

You could also make the addConversation into an action which also is a transaction:

@action
addConversation(conversation) {
  this.conversations.push(conversation);
  console.log('Added conversation');
}
like image 93
Tholle Avatar answered May 21 '26 22:05

Tholle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!