0

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});
        }
}
2
  • 1
    Setting state is asynchronous in React - you cannot log it immediately after setting it. You can use the callback option of this.setState which will always execute its callback function after state is set. Commented Nov 21, 2020 at 12:54
  • as @lawrence-witt said you can't, but you can console inside the render() method Commented Nov 21, 2020 at 12:57

1 Answer 1

3

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)
})

)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.