I try to get the current value of my selectbox but the function returns the previous value here is my code import React from 'react';
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
vlaue: '',
select: '',
};
}
result = (e) => {
this.setState({ vlaue: e.target.value, });
};
select = (event) => {
this.setState({ select: event.target.value });
console.log(this.state.select);
};
render () {
return (
<form>
<label>your name</label>
<input type="text" onChange={this.result} />
<select value={this.state.select} onChange={this.select}>
<option value="JS">JS</option>
<option value="php">php</option>
<option value="python">python</option>
</select>
</form>
)
};
};
export default Form;
for example when I select js then select php the function return js.
CodePudding user response:
It does that because state updates are asynchronous. You're doing a console.log before state update happens. Hence it prints the old value.
You can update your code to this to make it work:
printSelectedValue = () => {
console.log(this.state.select);
}
select = (event) => {
this.setState({ select: event.target.value }, this.printSelectedValue)
};
The second parameter of setState is a callback function which is called after state is updated.
CodePudding user response:
The setState
is asynchronous and cannot expect the output in the next line of code.
Add the console.log
inside the callback of setState
like below to check the updated value:
select = (event) => {
this.setState({ select: event.target.value }, () => {
console.log(this.state.select);
});
};
class Form extends React.Component {
constructor(props) {
super(props);
this.state = {
vlaue: "",
select: ""
};
}
result = (e) => {
this.setState({ vlaue: e.target.value });
};
select = (event) => {
this.setState({ select: event.target.value }, () => {
console.log(this.state.select);
});
};
render() {
return (
<form>
<label>your name</label>
<input type="text" onChange={this.result} />
<select value={this.state.select} onChange={this.select}>
<option value="JS">JS</option>
<option value="php">php</option>
<option value="python">python</option>
</select>
</form>
);
}
}
ReactDOM.render(<Form />, document.querySelector('.react'));
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<div class='react'></div>