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']);
}
}
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');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With