0

I'm very new in React Native and I'm working on application which is retrieving a listings from API and the backend is using NoSql database. My goal is to sort the listings via date of adding. Here is the method which is adding the listings:

const renderListingContent = (listingList, containerStyle = {}) =>
    listingList?.length === 0 ? (
      <View style={{ paddingTop: 155 }}>
        <EmptyListing
          type={listingStatus}
          setShowRadiusModal={setShowRadiusModal}
        />
      </View>
    ) : (
      <>
        <View style={[styles.listingsWrapper, containerStyle]}>
          {listingList?.map(listing => (
            <ListingPreview
              listing={listing}
              key={listing?.guid}
              onPress={() => {
                navigation.navigate('ViewListing', {
                  listingId: listing.guid,
                  onGoBack: () => setShouldRefresh(false),
                });
              }}
            />
          )) || null}
        </View>
        {!noMoreData && (
          <View style={styles.bottomListingLoader}>
            {isAddLoading ? <Loader /> : null}
          </View>
        )}
      </>
    );

If I have to share any other code please let me know.

1 Answers1

0

One might argue that you should be passing a sort parameter to the API instead.

One reason would be that you might have 100 results locally but 10k results remotely, you'd expect it to be sorting on the whole dataset.

Another reason would be to avoid doing client-side array operations that could be a performance bottleneck on lower-end devices.

But, if your goal is to sort a listing by date of adding, then it should be the same as How to sort an object array by date property?.

Here is how it could look like in your use case:

const ListingContent = ({ listingList, handleOnPress }) => {
 
  // "React.useMemo" will, instead of sorting on every render,
  // only sort if the "listingList" prop actually changes.
  const sortedList = React.useMemo(() => {
    return listingList.sort((listingA, listingB) => {
      const addedDateA = new Date(listingA.addedDate);
      const addedDateB = new Date(listingB.addedDate);
      return addedDateB - addedDateA; // descending order
    });
  }, [listingList]);

  return sortedList.map((listing) => (
    <ListingPreview
      key={listing?.guid}
      listing={listing}
      onPress={handleOnPress}
    />
  ));
};