Search code examples
javascriptreactjssetstate

React State is not assigning properly with setState


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 ?


Solution

  • 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.