dsdsa
dsdsa

Reputation: 77

react native states returns undefined inside setinterval function

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

Upvotes: 1

Views: 789

Answers (3)

Tim
Tim

Reputation: 10709

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

Upvotes: 2

th3g3ntl3m3n
th3g3ntl3m3n

Reputation: 151

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)

}

Upvotes: 0

Mahamat
Mahamat

Reputation: 11

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

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

Upvotes: 0

Related Questions