Back to tutorials
  • 1Before We Start
  • 2Dependencies
  • 3Components
  • 4Configuring State
  • 5Rendering Data
  • 6Event Listeners
  • 7Updating State
  • 8Adding Todos
Metal.js HomeMetal.js
  • Documentation
Learn to create a simple Todo App with Metal.js and Soy

Updating State

Now you're ready to update the state in TodoApp. In the last step, you added an event listener:

// TodoApp.js

class TodoApp extends Component {
    ...

    handleTodoClick(event) {
        alert(event.index);
    }
}

Now all you need to do is update the state so that the template rerenders:

// TodoApp.js

class TodoApp extends Component {
    ...

    handleTodoClick(event) {
        this.toggleTodo(event.index);
    }

    toggleTodo(clickedIndex) {
        this.todos = this.todos.map((todo, index) => {
            if (clickedIndex === index) {
                todo.done = !todo.done;
            }
            return todo;
        });
    }
}

This toggles the done property of the todo that was clicked. Simply setting the this.todos property to a new array of todos triggers a rerender, passing the data to the child components. Your markup should look like this once you've clicked a todo item:

<div class="todo-app">
    <ul>
        <li class="todo-item todo-item-done">Todo 1</li>
        <li class="todo-item">Todo 2</li>
    </ul>
</div>

Completed Todo

I updated the state