Search code examples
reactjsmobxmobx-react

MobX not updating React Component when computed array is changed


I have a list of todos in store which is not sorted. A computed value is added to store that returns sorted todos. The React Component is using sortedTodos to display the list. Whenever the todos list changes, the component is not re-rendered, if I use todos directly it works.

export class TodoStore {
  @observable todos: Todo[] = [
    { description: "testing", createdAt: new Date(), isCompleted: false },
  ];

  @computed get sortedTodos(): Todo[] {
    const sortedTodos = this.todos.sort(
      (a, b) => a.createdAt.getTime() - b.createdAt.getTime()
    );
    return sortedTodos;
  }

  @action addTodo = (description: string) => {
    this.todos.push({
      description,
      createdAt: new Date(),
      isCompleted: false,
    });
  };
}


Solution

  • I found the solution for the problem.

    Instead of directly assigning an array, I used observable.array and it works.

    export class TodoStore {
      @observable todos: Todo[] = observable.array();
    
      ...
    }
    

    Not completely sure why so but it works. I think the reason is that by using a regular array, the objects inside are not observables by default, when using observable.array the objects of array themselves are observables.