Flatlist keyExtractor returns "TypeError: null is not an object" when data is null

Viewed 244

I have the following React Native Flatlist:

<FlatList
            data={dataOnDevice}
            renderItem={({ item }) => {
              return (
                <RowItem
                  id={item.id}
                  key={item.id}
                  text={`ID: ${item.id} Name: ${item.name} Group: ${item.group}`}
                  onPress={() => {
                    navigation.pop();
                  }}
                  rightIcon={
                    <View style={styles.icon}>
                      <Entypo name="trash" size={20} color={colors.white} />
                    </View>
                  }
                />
              );
            }}
            ItemSeparatorComponent={() => <RowSeparator />}
            ListFooterComponent={() => (
              <View style={{ paddingBottom: insets.bottom }} />
            )}
            ListEmptyComponent={() => listEmptyComponent()}
            keyExtractor={(item) => item.id.toString()}
          />

This works fine when I have data in the list but when dataOnDevice is null, I get an error:

TypeError: null is not an object (evaluating 'item.id.toString')

This has happened after a refactoring which causes dataOnDevice to be null. My understanding is that ListEmptyComponent should be able to handle that...

How can I prevent this error with the keyExtractor?

For now I found a way around this by adding:

keyExtractor={(item) => {              
  if (item !== "") {              
    item.id.toString();             
  }            
}}

But I'm open to any cleaner way of handling it...

1 Answers

You should check that ID is not null

in keyExtractor

  if (item?.id !== "") {              

Through? You check if the value exists if it does not return false

This way you can know that you are approaching an existing value and avoiding an abnormal shot

Read more about Ternary Operator

Related