I'm having a problem with setState not updating my todoItems array. I read through the other posts here that have dealt with the same issue. In my addTodoItem() I changed this.setState to a function and I'm now using the spread operator, A new item is being generated in the array. This is what logs:
(4) [{…}, {…}, {…}, {…}]0: {id: "1", item: "Learn React."}1: {id:
"2", item: "Do Yoga."}2: {id: "3", item: "Be kind."}3: {id: "4",
item: "Have Fun"}length: 4__proto__: Array(0)
App.js:36 todo: Have Fun
But it doesn't actually update the array. When I refresh it reverts to the original state. From what I read I think I'm having the state updating async issue. What am I missing?
class App extends Component {
constructor(props) {
super(props);
this.state = {
value: '',
listItemValue: props.value || '',
todoItems: [
{id: _.uniqueId(), item: 'Learn React.'},
{id: _.uniqueId(), item: 'Do Yoga.'},
{id: _.uniqueId(), item: 'Be kind.'}
]
};
this.addTodoItem = this.addTodoItem.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
let value = event.target.value;
this.setState({
value: this.state.value,
listItemValue: value
});
}
handleSubmit(event) {
event.preventDefault();
this.setState({
value: '',
listItemValue: ''
});
}
addTodoItem = () => {
let todoItems = this.state.todoItems.slice();
todoItems.push({
id: _.uniqueId(),
item: this.state.listItemValue
});
this.setState(prevState => ({
todoItems: [
...prevState.todoItems,
{
id: _.uniqueId(),
item: this.state.listItemValue
}
]
}))
};
render() {
return (
<div className="App">
<h1>Todo List</h1>
<TodoListForm name="todo"
onClick={()=>this.addTodoItem()}
onSubmit={ this.handleSubmit }
handleChange={ this.handleChange }
value={ this.state.listItemValue } />
<TodoList todoItems={ this.state.todoItems }/>
</div>
);
}
}
addTodoItemyou are updating your state asynchronously, while onhandleChangethe state is being updated synchronously. I'm not sure, but there may some kind of race condition... and I would try to make all state updates in asynchronous way, passing a function as an argument ofsetState.