skip to Main Content

Good day, I have a flat list that renders some events, that have a startDate property, which functions as the title of the event. My question is, how can I compare the items in the renderItem function so that if two events have the same startDate I show it only once.


const renderItem = ({ item, index }) => {
    return (
      <>
        <Text style={[sharedStyles.bigTextBold, { marginVertical: 20 }]}>{moment(item.startDate).startOf('day').isSame(moment(item.startDate).startOf('day'))}</Text>
        <Event
          containerStyle={index !== 0 && { marginBottom: 10 }}
          key={item._id}
          data={item}
          onPress={() => {
            Nav.navigate('CommunityCalendarView', {
              data: item,
              communityId,
              propertyId
            })
          }}
        />
      </>
    )
  }

  <FlatList
            style={[styles.flatListContainer]}
            data={data}
            renderItem={renderItem}
            onEndReachedThreshold={0.5}
            onEndReached={handleLoadMoreEvents}
            keyExtractor={item => item._id}
            contentContainerStyle={{ paddingBottom: 60 }}
            ListFooterComponent={() => {
              return (
                <>
                  {loading && <ActivityIndicator size='small' color={EStyleSheet.value('$green')} />}
                  {emptyState && !data.length &&
                    <Text
                      style={[sharedStyles.textLight,
                        { textAlign: 'center', justifyContent: 'center', flex: 1, paddingHorizontal: 20 }
                      ]}
                    >
                      {translate('community.calendar.noEventsSearchResultText')}
                    </Text>}
                </>
              )
            }}
          />}

In my code I pass the item and the index, but I don’t really know how to compare the different items while they are being rendered

2

Answers


  1. You need to filter your data to have a unique data set.

    data = {data.filter((value, index, self) =>
      index === self.findIndex((t) => (
        t.startDate == value.startDate
      ))
    )}
    
    Login or Signup to reply.
  2. I think you should do that before the FlatList consume the data.

    const data = [
      
    {
      startDate: "fooDate",
    user:"Foo"},
    
    {startDate:"barDate",
    user:"Bar"},
    
    {startDate:"bazDate",
    user:"Baz"},
    
    {startDate:"barDate",
    user:"Bar"}
    ]
    
    const isSameStartDate = (value) => (el) => el.startDate === value.startDate
    
    const newData = data.filter((value, index, array) => index === array.findIndex(isSameStartDate(value))
    )
    

    Then just:

    <FlatList data={newData} {…props} />
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search