Search code examples
react-nativemethodsinvoke

calling a method within another method in react native


hi everyone i'm just learning react native and i have a problem. When I first start the application, I want to print a log "call _methodA" and "value is true". The log should be:

call _methodA
value is true

The exercise consists in calling another method within one method. My code is:

export default class App extends Component {
  constructor(){
    super();
    this.state = {firstLaunch: null};
}
_methodA() {
   console.log("call _methodA"); 
}

_methodB() {
   console.log("call _methodB"); 
}

componentDidMount(){
    AsyncStorage.getItem("alreadyLaunched").then(value => {
        if(value == null){
             AsyncStorage.setItem("alreadyLaunched", JSON.stringify(true)); 
             this.setState({firstLaunch: true});
             this._methodA();
             console.log("value is true");
        }
        else{
             this.setState({firstLaunch: false}); 
              this._methodB();
             console.log("value is false");          
        }})
}
render(){  
}
}

At the first start of the application the Log is: "value is true" without also printing "call _methodA"; it's like it fails to invoke method A, why? how can I invoke a method inside another method?


Solution

  • bind methods with .bind in constructor

    this._methodA()=this._methodA.bind(this);
    this._methodB()=this._methodA.bind(this);
    
    

    or you can use arrow functions

    _methodA=()=>{
    //your code
    }
    _methodB=()=>{
    //your code
    }