Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js setState not working [duplicate]

Im a noob in React and trying to make a simple app for water phases where the user enters a number and then based on the value it should display the state of water, for example if he enters 212 it should say gas and for 12 it should say solid, but for some reason its not displaying the values correctly, Any help is greatly appreciated!!!

class App extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            msg: "liquid",
            temp: 0
        };
        this.handlenum1Change = this.handlenum1Change.bind(this);
    }

    handlenum1Change(evt) {
        console.log(evt.target.value);
        this.setState({
            temp: Number(evt.target.value)
        });

        let temp = this.state.temp
        if (temp > 100) {
            this.setState({
                msg: "boiling"
            })
        } else if (temp < 32) {
            this.setState({
                msg: "frozen"
            })
        } else {
            this.setState({
                msg: "liquid"
            })
        }
    }

    render() {
        return (
            <div>
                <h1> {this.state.msg} </h1>
                <form className="form-inline">
                    <div className="form-group">
                        <label> Temp: </label>
                        <input type="number"  onChange={this.handlenum1Change} className="form-control" />
                    </div>
                </form>
            </div>
        );
    }
}

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
like image 695
Leon Bogod Avatar asked Mar 08 '26 14:03

Leon Bogod


1 Answers

setState is asynchronous and won't update the state straight away. It collects multiple state changes before updating. That means, that this.state won't hold your new value right away.

Or to quote the React docs here:

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. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied. If you need to set the state based on the previous state, read about the updater argument below.


Instead, do it the other way around and work with the user input before setting the new state. That way you can also collectively set both, the temperature and the message at once:

const temp = Number(evt.target.value);
let msg = '';
if (temp > 100) {
  msg = 'boiling';
} else if (temp < 32) {
  msg = 'frozen';
} else {
  msg = 'liquid';
}

this.setState({
  temp,
  msg,
});
like image 182
lumio Avatar answered Mar 10 '26 05:03

lumio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!