Search code examples
reactjsnativesetstate

react native calling a fat arrow function after setState: function is not defined


On button pressed my App calls the handlePress function, which returns random objects from an array.

handlePress function:

handlePress = () => {
      this.setState({
        vitamin: getRandomIngredient(vitaminArray),
      }, ()=> matchMealPreference())
    }

If I replace matchMealPreference() with a console.log() it works just fine.

After setting the new states I want to call another function immediately with a fat arrow. Otherwise I run into async problems.

The matchMealPreference function looks like this:

matchMealPreference = () => {
      if(this.props.mealPreference === this.state.protein.getIngredientFlag()){
        return state
      } else {
        handlePress()
      }
    }

The function to get a random object from an array:

function getRandomIngredient (arr){
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
}

I get the error:

reference error. matchMealPreference is not defined 

I'm almost certain that I'm missing something trivial. But I've been stuck at that problem for over a day now, so I thought I'd turn to you for help.

  • Is there another way to call the matchMealPrefence without the asynchronous problems occuring?

  • Is it at all possible to call a function at the position where matchMealPreference is called?

  • Is it unwise to call the handlePress function within the matchMealPrefence function again?

Any help is much appreciated

Edit: Vijay Menon's answer was correct. I needed to add 'this'. Thanks!


Solution

  • You have to reference "matchMealPreference" with "this" keyword inside setState. You would have to do the same for calling "handlePress" inside "matchMealPreference" function

    https://codesandbox.io/s/542919430l

       changeStr = () => {
         this.setState({str:"Changed"})
       }
        click = () => {
          this.setState({num:this.state.num+1},() => {
            this.changeStr()
          })
        }