I'm new to React and I'm following an online tutorial. The instructor presented the code below as part of a Todo App. It is the logic for adding a new todo item (object) to the state.
var TodoApp = React.createClass({
getInitialState: function() {
return {
todos: {}
};
},
addTodo: function(todo) {
var timestamp = (new Date()).getTime();
this.state.todos[`todo-${timestamp}`] = todo;
this.setState({
todos: this.state.todos
});
}
});
1. In this case, is it a good practice to assign the todo object to the state before calling this.setState()? (This SO question gives some related information.)
2. Wouldn't it be better to spread the todos as below?
3. Alternatively, is there a better way to update state in this setup?
var TodoApp = React.createClass({
getInitialState: function() {
return {
todos: {}
};
},
addTodo: function(todo) {
var timestamp = (new Date()).getTime();
this.setState({
todos: {...this.state.todos, [`todo-${timestamp}`]: todo}
});
}
});