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>
);
}
}