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()
As you have done for myPutFunction
you have to bind this
in your then callback
then(function(res) { /*...*/}.bind(this))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With