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.
>Solution :
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>