0

I am learning ReactJS and am working on developing a Todo list app.

In my page I have a task textbox and a button to add tasks to items array. I am facing one issue, when I click on the Add task button to add my first task it seems its not adding it the first time and then when I add my second task the first one is added but not the second one and so on. I am using console.log(this.state.items) to know what items do I have and the issue is the previous item is added the next time.

I am just learning React and not an experienced person on the skill, would really appreciate any help and explanation on the issue am facing and how do I resolve it.

Below is the code I have written so far.

import React, {Component} from 'react';    
class TodoList extends Component{    
  addTask(event){    
      //Get task Value
      var task = this.refs.name.value;

      if(task!==""){
          var newItem = {
              text : task,
              key : Date.now()
          }

          this.setState({
              items : this.state.items.concat(newItem)
          });

        this.refs.name.value = ""; //Blank out the task input box
      }

      console.log(this.state.items);
  }   



  constructor(props){
    super(props);

    this.state = {
        items : []
    };
    this.addTask = this.addTask.bind(this);
  }
  render(){
    return(
    <div className = "todolistMain">
        <div className="header">
            <form>
              <input placeholder="Enter Task" id="name" ref = "name"></input>
                <button type="button" onClick={this.addTask}>Add Task</button>
            </form>
        </div>
    </div>
    );
  }
}

export default TodoList;
Shahrukh
  • 740
  • 7
  • 25
Vir
  • 25
  • 4

1 Answers1

3

You are seeing console.log(this.state.items) displaying previous state because,setState is an asynchronous call.

Issue :- Console log is printed before setState is performed.

Solution :- Use Callbacks,CallBacks are used, when we want to perform some operations/console.log when state is changed.

Update Code :-

this.setState({
        items: this.state.items.concat(newItem)
      },()=>{
        this.refs.name.value = "";
        console.log(this.state.items);
      });

Hope this helps,

Cheers !!

Sahil Arora
  • 491
  • 3
  • 10