tkamath99
tkamath99

Reputation: 649

SetState inside function of React class component

I am determining the users OS platform and setting state based on it. I have a function which determines the users OS platform and i am trying to setState, But the property inside the state is always returning false.

Here is my Component.

class HowtoDownload extends React.Component {
constructor(props) {
super(props);
this.state = {
                windows: false,
                chromebook: false,
                ipad: false,
                mac: false,
}
        componentDidMount() {
            console.log("How to Download Component Mounted");
            this.getUserPlatform();
            console.log(this.state.windows);
        }
 getUserPlatform = () => {
            var OSName = "UnknownOS";
            if (navigator.appVersion.indexOf("Win") !== -1)
                OSName = "Windows";
                this.setState({windows: true});
        }
}

Upvotes: 0

Views: 312

Answers (1)

Yasmin
Yasmin

Reputation: 343

componentDidMount() is invoked immediately after a component is mounted. So after the state has been updated, it won't called again.

To see the updated result, you can use the componentDidUpdate() lifecycle method. You can fetch the result in render() method to.

Also React updates state asynchronously, if you want to see the updated state when it's done, you should use the callback function of setState which gets fired as soon as the state gets updated:

this.setState({windows: true}, () => {
  console.log(this.state.windows)
})

)

Upvotes: 3

Related Questions