How to do conditional rendering after fetch in react native?I wan't to render components after
1.Successful fetch with the responseData
2.Network request fails
3.If there is empty responseData
returned from server
For now I'm displaying only the successful result.I want to display the failure case also.How do I render Text
component after unsuccessful fetch.Following is my code
onPressSubmit() {
fetch("xxxx", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
url: this.state.url
})
})
.then((response) => response.json())
.then((responseData) =>
{
this.setState({
res:responseData.message,
showLoading: false
}, () => console.log(this.state.res));
}).catch((error) => {
console.error(error);
});
}
renderArticle(){
const {title} = this.state.res;
const {image} = this.state.res;
const {text} = this.state.res;
const {id} = this.state.res;
const {author} =this.state.res;
const {html} = this.state.res;
return (
<TouchableOpacity
onPress={() => Actions.addNewarticle({heading:title, authorname:author, description:text, htmlcon:html})}
>
<CardSection>
<View style={{ flexDirection: "row" }}>
<Image
source={{ uri:image }}
style={styles.thumbnail_style}
/>
<Text style={styles.textStyle}>{title}</Text>
</View>
</CardSection>
</TouchableOpacity>
);
}
render(){
return(
<View>
{this.renderArticle()}
</View>
);
}
Create renderNetworkFailure
method in which you can display whatever you want. Into render
method. check your response data is available or not? I have check blank string.
render(){
const isResponseData = (this.state.res == '') ? this.renderNetworkFailure() : this.renderArticle()
return(
<View>
{isResponseData}
</View>
);