0

I'm creating a very basic todo app. But I'm getting an issue with pushing todos into an array and assigning them to the state.

  constructor(props){
    super(props);
    this.state = {
      todo : '',
      todos : []
    };
  };

  todoValue(todo){
    console.log(`Received the todo in the App : ${todo}`);
    this.setState({todo});
    console.log(this.state.todo);
  }

Here when I click a button I'm receiving todo value in todo argument of todoValue function. But it doesn't assign to the state on the event. It does assign the value to the state on next event.

As an example if I receive todo value as one in first event and todo value as two in next event this is what I'm getting.

Screenshot of the output

I want to assign the todo value to the state on the button click (not on the next event)

How can solve this ?

Thidasa Pankaja
  • 930
  • 8
  • 25
  • 44

2 Answers2

4

setState is an async operation but it does allow a callback to be triggered when the operation is complete. Change your code to

this.setState({ todo }, () => console.log(this.state.todo));

and you'll see the latest changes you made to the state.

Andy
  • 61,948
  • 13
  • 68
  • 95
1

setState is async, so react can batch several call to setState in order to improve performance.

As said above, either use the callback function of setState OR the componentLifeCycle componentDidUpdate

ScreamZ
  • 581
  • 4
  • 16