Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

this.props undefined in fetch response-react native [duplicate]

I'm sending some JSON data to a server with PUT method using fetch. I would like to pop to the previous page if and only if server response is positive.

This is my code:

async  myPutFunction() {

    console.log(this.props); //here props are defined!

    var dataArray=[]; //array with data to be sent

    //operations on dataArray

    await fetch('http://myURL', {
      method: 'PUT',
      headers: {
         'Accept': 'application/json',
         'Content-Type': 'application/json',
      },
      body: JSON.stringify(dataArray)
    }).then(function(res) {
      if (res.status===200) {
        console.log("OK!")
        console.log(this.props); //here props are undefined
        this.props.navigator.pop();
      } else {
        console.log("error: "+res.status);
      }
    })
}

However, inside the 'then' block props are undefined and this.props.navigator.pop() throws an exception.

My put function is invoked in this way inside render():

<TouchableOpacity style={styles.saveStyle}
                        activeOpacity={0.5}
                        onPress={this.myPutFunction.bind(this)}>
        <Image source={saveImg} style={{resizeMode: 'cover'}} />
</TouchableOpacity>

I cannot figure out why props are undefined inside that portion of code while being defined in the rest of myPutFunction()

like image 650
user6282639 Avatar asked Jan 05 '23 05:01

user6282639


1 Answers

As you have done for myPutFunction you have to bind this in your then callback

then(function(res) { /*...*/}.bind(this))
like image 197
Steeve Pitis Avatar answered Jan 13 '23 09:01

Steeve Pitis