0
votes

enter image description here

I don't understand why state returns undefined My code is this:

class s extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
          name:null,
          uri:null,
          fbid:null,
        };     
    }

  componentDidMount() {
   setInterval(function(){..
    if(this.state.fbid!=null){..
    ..),1000}

this.state.fbid => is undefined

3
Have you tried logging this.state and using !== instead off !=? And is it undefined in the didMount or? Please clarify a little - jovi De Croock
... if(this.state.fbid!=null){ ...runs inside ...setInterval(function(){.. - dsdsa
alert(this.state.uri); works but inside setinterval is not working - dsdsa

3 Answers

1
votes

this is out of context of your function, reason because setInterval function creates their own scope. Try arrow functions instead.

componentDidMount() {

    setInterval(() => {
      if(self.state.fbid!=null){
          // do something
      };
    }, 1000);
}
0
votes

i guess, in react custom component names should start with capital letter.

https://codesandbox.io/s/kolwq50kj5, working as expected.

0
votes

defining functions will create their own scope here. and this bounds to function scope. because state is not in function scope you can't access it hence undefined. try using arrow functions instead:

componentDidMount() {

  setInterval(() => {
    //do anything
  }, 1000)

}