Quantcast
Channel: Active questions tagged react-native+android - Stack Overflow
Viewing all articles
Browse latest Browse all 29622

How do I perform conditional rendering in my FlatList RenderItem component correctly?

$
0
0

I've created a function to get a photo from a server which receives an associated ID number as an input, the function will return response code like 200 if there is a photo associated with the item. Else if response code is 400 or 404, it should return null. But when I call the function inside the JSX element of RenderItem component of my FlatList, the if check to see if the returned value is not null - is sort of working. It would display the component for all of the list item instead of the one that actually has a photo. Here is the part of the renderitem code for my FlatList component which calls the function:

{this.myGetPhotoFunction(item.IDVALUE) !== null ? (
                      <View style={mystyle}>
                        <Image
                          style={mystyle}
                          source={{
                            uri: `http://MYSERVERURL/chits/${item.IDVALUE}/photo`
                          }}
                        />
                      </View>
                    ) : (
                      <Text>NO IMAGE</Text>
                    )}

Below is my function to get the photo from a server:

myGetPhotoFunction = async IDVALUE => {
    try {
      const response = await fetch(
        `http://MYSERVERURL/chits/${IDVALUE}/photo`,
        {
          method: 'GET'
        }
      );

      if (response.status === 200) {
        return response.status;
      } else if (response.status === 400 || response.status === 404) {
        console.log('\n' + response.status + '\n');
        return null;
      }
    } catch (error) {
      console.log('\nError fetching photo: ' + error);
    }
  };

Right now, the if check inside the RenderItem component of my Flatlist is rendering the component for all list item. Which I do not want. I want the list to render the component for only the one that has a returned promise value of 200.

Here is what my app is rendering: enter image description here

As you can see the list is rendering the Image component for all list item because of the white spaces inside each list item. I want the item to only display the image if there is an actual image to display.


Viewing all articles
Browse latest Browse all 29622

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>