user6282639 user6282639 - 1 year ago 80
Javascript Question

this.props undefined in fetch response-react native

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(this.props); //here props are undefined
} 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}
<Image source={saveImg} style={{resizeMode: 'cover'}} />

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

Answer Source

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

then(function(res) { /*...*/}.bind(this))