findAffs
findAffs

Reputation: 103

how to render item only if there is data?

I am using axios to get json data from a link , I am calling that link from componentWillMount function , and then I store data in the state , my render method contains a FlatList that should display that data , all works fine , I only want that I can make a condition , I want my render method to display Faltlist only if there is some data in the state otherwise display a simple message saying that there is no data to show , I dont know why it didn't work with my code , could please help :

this is my flatlist in render method :

<FlatList
        data = {this.state.data}
        renderItem = {this.renders}
        keyExtractor ={this.keyextractor}
        />

and this is the renders function that is called by flatlist :

renders({item}){
if(item.length > 0)
{
    return(
      <Itemz
      offer={item}
      />
  );
}else{
return(
    <View><Text>No Data to show</Text></View>
);
  }

Upvotes: 0

Views: 345

Answers (2)

Brayan Salazar
Brayan Salazar

Reputation: 334

you can try to use FlatList prop ListEmptyComponent, Rendered when the data is empty.

https://facebook.github.io/react-native/docs/flatlist#listemptycomponent

Upvotes: 3

dentemm
dentemm

Reputation: 6379

You need to put your condition check in the render() function, since you only want to show the FlatList when data is present.

render() {

  const {data} = this.state;

  if (data.length > 0) {
    return <FlatList data={data} renderItem={this.renderItem} ... />
  } else {
    return (
      <View>
        <Text>No Data to show</Text>
      </View>
    );
  }
}

renderItem = ({item}) => {
  return <Item offer={item} />
}

Upvotes: 0

Related Questions