1

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>
);
}

2 Answers 2

2

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>
);
Sign up to request clarification or add additional context in comments.

4 Comments

Can I give one more condition that if responseData is empty?
Why not? It's up to your requirement.
So how would that be? Could you please check this const isResponseData = (this.state.res == '') ? this.renderNetworkFailure() : this.renderArticle() :this.renderEmptyData()
No its an ternary operator. its like if else. ? is if and : is else
0

I think more precisely this is how your answer would look like, and if you want to show for the network failure as well then you must keep a state variable for it also.(Im also a beginner in react-native please correct if there is anything wrong)

render(){
return(
<View>
{(this.state.err)?this.networkFailure():({this.state.res.length? this.renderArticle():this.renderNothing()})}
</View>
)
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.