Reordering Array for Todos in MST Mobx State Tree

837 Views Asked by At

I would like to reorder arrays when using mobx state tree.

Say I have this example taken from the example page. How do I get to reorder my ToDos in the TodoStore.

As a simplified example, say my todos are ['todo1, todo2'], how do I change them so that the new array is ['todo2, todo1']?

const Todo = types
    .model({
        text: types.string,
        completed: false,
        id: types.identifierNumber
    })
    .actions((self) => ({
        remove() {
            getRoot(self).removeTodo(self)
        },
        edit(text) {
            if (!text.length) self.remove()
            else self.text = text
        },
        toggle() {
            self.completed = !self.completed
        }
    }))

const TodoStore = types
    .model({
        todos: types.array(Todo),
        filter: types.optional(filterType, SHOW_ALL)
    })
    .views((self) => ({
        get completedCount() {
            return self.todos.filter((todo) => todo.completed).length
        },            
    }))
    .actions((self) => ({
        addTodo(text) {
            const id = self.todos.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1
            self.todos.unshift({ id, text })
        },
        removeTodo(todo) {
            destroy(todo)
        }, 
    }))

export default TodoStore

Thanks a lot!

1

There are 1 best solutions below

2
On

If you want move the second todo to the first index in the array you could create a new action and splice the second todo out and then unshift it back in:

swapFirstTwoTodos() {
  const secondTodo = self.todos.splice(1, 1)[0];
  self.todos.unshift(secondTodo);
}