Reputation: 181
I am trying to update the state of the variable "selectedPlayer" however when I setState function the state of this variable does not update, I have tested this through console logs as you can see below.
Below is how I am trying to set the state of the variable and the some of this class file for your knowledge
this.setState({ selectPlayer: player });
this is some of the Component file and a function which i am using to update the state.
class StatApp extends Component {
constructor(props) {
super(props);
this.state = {
selectedPlayer: 'dassdasda',
};
this.selectPlayer = this.selectPlayer.bind(this);
}
selectPlayer = e => {
e.preventDefault();
// console.log(e.target.value); //will give you the value continue
// Store Value
const selectPlayer = this.state.selectedPlayer;
console.log(this.state.selectedPlayer);
console.log(selectPlayer);
// Test to see if we are getting the value from the playerButton
const player = e.target.value;
console.log(player);
this.setState({ selectPlayer: player });
console.log(selectPlayer);
};
Upvotes: 0
Views: 425
Reputation: 1759
I guess it'a typo. try changing
this.setState({ selectPlayer: player });
to
this.setState({ selectedPlayer: player });
Find the other answer for the updated state not being printed on console.
Upvotes: 0
Reputation: 629
setState is asynchronous, so when you are console logging it, state has not yet been updated. You can use the callback form of setState to get the updated state:
this.setState(
{ selectPlayer: player },
() => console.log(this.state.selectPlayer)
);
Upvotes: 3