Undefined is not an object while filtering a Flatlist

Viewed 268

I'm trying to filter some data in react native, but when the data come from a JS file it works when they come from a firebase DB it says "undefined is not an object (evaluating MeasuresList.filter)"

this is the code

<FlatList style={styles.flatList}
          data = {ExercisesList.filter(item => item.muscle === "shoulders")}}
          keyExtractor={(item) => item.id}
          renderItem={({ item }) => 
                     {item.name}
                        }
                    />

If I delete the filter part and I get into the screen I can see the flatlist with all the exercises, if then I add the filter part and I save I can see the elements filtered and it works. The problem is that I can't get into this page when I have the filter code added, even if it seems to work, why is "MeasuresList.filter" undefined just before I get into the screen?

2 Answers

Try below:

Array.isArray(MeasuresList) && MeasuresList?.filter

You should also set the default value of MeasuresList as []

[Undefined is not an object] means, MeasuresList is undefined. In this case, [ExercisesList.filter] is the same as the [undefined.filter].

So you should check if the MeasuresList is undefined or defined value.

{ExercisesList? ExercisesList.filter(item => item.muscle === "shoulders") : []}

Please let me know if it works for you or not. Thanks.

Related