0

I created this code where On click of a button its id is concatenating in the array 'allInterest'.

But here I noticed that, its setting state one state behind.Like If I click on the button for the first time then in the console, its array is blank but when I click on another button then it's taking first clicked button Id and same goes on further.

please guide me why such thing happening.Thanks in anticipation

 export default class Test extends Component {
  constructor(props, context) {
    super(props, context);

    this.handleChange = this.handleChange.bind(this);
    this.state = {
      value:'',
      numbers:[1, 2, 3, 4, 5],
      posts : [
        {id: 1, topic:"Animal"},
        {id: 2, topic:"Food"},
        {id: 3, topic:"Planet"},
        {id: 4, topic:"Nature"},
      ],
      btnSelected:false,
      allInterest:[],
    };
    console.log(this.state);
  }

  handleChange(e) {
    //console.log(e.target.value);
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value});
    console.log(this.state)
   }

   getInterest(id){
     console.log(id);
     console.log(this.state.allInterest)
    // if(this.state.allInterest.length>0 )
    // {
    //   console.log("Yes we exits");
    // }
    // else
    // {
      console.log(id)
      // this.setState({
      //   allInterest:this.state.allInterest.concat(id)
      // })
      this.setState((prevState) => ({
        allInterest: prevState.allInterest.concat([id])
      }));  
    // }
    console.log(this.state)

   }



  render() {
    // numbers = [1, 2, 3, 4, 5];
    return (
      <div>

      <div className="signupApp">
      Test
      {this.state.listobj}



      { this.state.posts.map((posts,index) => 
        <li key={'tab'+index} class="btn btn-default" onClick={()=>this.getInterest(posts.id)} onChange={() => this.handleChange(this.event)}>{posts.topic}</li>
        )}

      </div>
  </div>
    );
  }
}
Mohammed Sabir
  • 157
  • 2
  • 2
  • 17
  • From the [documentation](https://reactjs.org/docs/react-component.html#setstate): *"setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall."* – Felix Kling Apr 29 '18 at 06:55
  • So indirectly it will not effect the things @ final click of submit button.Om final click it will always give us proper values of state? – Mohammed Sabir Apr 29 '18 at 07:13

0 Answers0