Reputation: 349
I am trying to handle a bad HTTP response with the fetch()
function in my React Native Component. I have used the code from here which suggests creating a module to handle response errors.
// ApiUtils.js
var ApiUtils = {
checkStatus: function(response) {
if (response.status >= 200 && response.status < 300) {
return response;
} else {
let error = new Error(response.statusText);
error.response = response;
throw error;
}
}
};
export { ApiUtils as default };
This is the code for my component:
import React, { Component } from 'react';
import {View, Text, StyleSheet, Slider, ListView} from 'react-native';
import GLOBAL from "../../Globals.js"
import ApiUtils from "../utils/ApiUtils.js"
class FetchedList extends Component {
constructor(props) {
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 != row2,
}),
loaded: false,
load_failed: false,
};
}
componentDidMount(){
this.fetchData();
}
fetchData(){
fetch(GLOBAL.BASE_URL + "/" + this.props.url_section + "/" + String(this.props.weekNo) + "/")
.then(ApiUtils.checkStatus)
.then((response) => {
return response.json()
})
.then((responseData) => {
if(responseData===[] || responseData.length === 0){
this.setState({
loaded: false,
load_failed: true,
});
}
else{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData),
loaded: true,
});
}
})
.catch(function(error){
console.log("Error:" + error.message);
this.setState({load_failed: true});
})
.done();
}
render() {
if (!this.state.loaded) {
if (this.state.load_failed){
return(
<View></View>
);
}
return this.renderLoadingView();
}
else{
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderComment}
/***//>
);
}
}
renderLoadingView() {
return (
<View>
<Text>Loading . . .</Text>
</View>
);
}
renderComment(comment){
return(
<Text style={styles.row}>{comment.content}</Text>
)
}
}
const styles = StyleSheet.create({
row: {
// backgroundColor: "antiquewhite",
flexDirection: "row",
justifyContent: "flex-start",
alignItems: "center",
height: 50
},
});
module.exports = FetchedList
I have made sure that the test server is currently giving 502 Gateway errors.
The behaviour I expect is that when an error is thrown by the line .then(ApiUtils.checkStatus)
it should be caught by the .catch
function and state should be updated by this.setState({load_failed: true});
. However, I get the error message ExceptionsManager.js:55 this.setState is not a function
.
I find this odd because the following works within the .then( . . .)
function above it:
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData),
loaded: true,
});
Why does the .catch
lambda not have access to this.setState
where the previous function does? Can I use .bind()
somehow?
If it is not possible to access this.setState
within the catch
function, how can I change state.load_failed
to true
if I get a poor HTTP response?
I attempted to pass the exception to the calling function and then change the state from the parent function, like so:
I changed the .catch()
function to this:
fetchData(){
fetch(GLOBAL.BASE_URL + "/" + this.props.url_section + "/" + String(this.props.weekNo) + "/")
.then(ApiUtils.checkStatus)
.then((response) => {
return response.json()
})
.then((responseData) => {
. . .
})
.catch(function(error){
console.log("Error!");
throw error;
})
.done();
}
and then changed the calling function like so:
componentDidMount(){
try{
this.fetchData();
}
catch(error){
this.setState({load_failed: true});
}
console.log(this.state.load_failed);
}
However, I then get a simple ExceptionsManager.js:55 Error
.
I tried removing .done()
, but the catch
block fails to handle the exception, state does not change and I get a warning: Possible Unhandled Promise Rejection (id: 0):
. I realise that this may have something to do with async functions in javascript and what the error is passed to, but I'm not 100% sure.
Environment: OSX 10.10, Android 4.1.2, React-native 0.29.2
Upvotes: 2
Views: 10435
Reputation: 3025
Your function is not running in the same context (this
value) as you expect. To solve this, either use an arrow function which keeps the same this
:
.catch(error => {
console.log("Error:" + error.message);
this.setState({load_failed: true});
})
or explicitly bind
to the current this
:
.catch(function(error){
console.log("Error:" + error.message);
this.setState({load_failed: true});
}.bind(this))
Upvotes: 8