kalculated
kalculated

Reputation: 319

Javascript .sort by time not working on array?

I have a flatlist which displays all the posts of users that the current user is following. This is normal in instagram, twitter, all social networks etc.

I want to display them chronologically, but it is not working.

The code works like this:

  1. I query Firestore for the current user's posts
  2. I have a list of UID's of ever user the current user is following
  3. I query Firestore for the posts of whoever the current user is following
  4. This returns all the posts I want
  5. The posts are in blocks. Ex, current user's posts are added to the array. Then user1 current user is following's posts get added. Then user2's posts get added. Etc.
  6. I attempt to run a .sort function provided by Javascript to order the posts chronologically

Here is the code for it (removed the doc fields as they are not important, except date_created):

getCollection = async (querySnapshot) => {
    const followingPosts = [];

    await Firebase.firestore() <----------------------- Get current users posts
    .collection('globalPosts')
    .where("uid", "==", Firebase.auth().currentUser.uid)
    .onSnapshot(function(query) {
        query.forEach((doc) =>  {
            const { 
                ....other fields

                date_created

                ....other fields
                } = doc.data();
    
                followingPosts.push({
                    ....other fields

                    date_created

                    ....other fields
                });
        })
    
    });

    querySnapshot.forEach(async (res) => {
        
        await Firebase.firestore() <-------------- get following users posts, uid after uid
        .collection('globalPosts')
        .where("uid", "==", res.data().uid)
        .onSnapshot(function(query) {
            query.forEach((doc) =>  {
                const { 
                    ....
                    date_created
                    ....
                    } = doc.data();
        
                    followingPosts.push({
                        ....other fields

                        date_created

                        ....other fields
                    });
            })

            
        
        });

         
    });
      
    
    followingPosts.sort(function(a,b){ <-------- How I try to sort the posts by date created

            return a.date_created.toDate() - b.date_created.toDate()

    })

    this.setState({
        followingPosts,
        isLoading: false,   
    });

}

Few notes:

  1. The posts are fetching correctly (only the people that current user is following's posts show up)

  2. The reason I am doing date_created.toDate() is because firestore timestamp objects are in nanoseconds and milliseconds. Whether I have date_created.toDate() or just date_created, it doesn't work.

  3. I am aware that I can query firestore and order by date_created, descending in the query. But since the posts are being queried sequentially, this only orders the individual blocks of posts, not the entire array

  4. I have tried putting the followerPosts.sort function INSIDE the query snapshot, after the for each. Not working either:

        querySnapshot.forEach(async (res) => {
    
        await Firebase.firestore() 
        .collection('globalPosts')
        .where("uid", "==", res.data().uid)
        .onSnapshot(function(query) {
            query.forEach((doc) =>  {
                const { 
                    ....other fields
    
                    date_created
    
                    ....other fields
    
                    } = doc.data();
    
                    followingPosts.push({
    
                        ....other fields
    
                        date_created
    
                        ....other fields
                    });
            })
    
    
    
        });
    
     followingPosts.sort(function(a,b){ 
    
            return a.date_created.toDate() - b.date_created.toDate()
    
    })
    
    });
    

EDIT: more information on date_created:

  1. Upon creation (Adding a new post to firestore), date_created is initialized like this:

        date_created: new Date()
    
  2. Within firestore, the above method of initializing date created looks like this:

enter image description here

  1. When I console log the date_created, I am returned a firestore timestamp object:

    t { "nanoseconds": 14000000, "seconds": 1610413574, }

  2. This is unusable for my purposes, so I convert this timestamp object using .toDate() when I pass the data to the flatlist:

        <FeedCellClass 
            ... other fields
            date_created={item.date_created.toDate()}
        />
    
  3. .toDate() converts it to this, which I can use for my purposes:

    2021-01-12T01:06:14.014Z

Let me know how to solve this issue.

Upvotes: 2

Views: 194

Answers (1)

kalculated
kalculated

Reputation: 319

I solved my problem - I was sorting in the wrong place. Here is the solution:

    querySnapshot.forEach(async (res) => {
        
        await Firebase.firestore()
        .collection('globalPosts')
        .where("uid", "==", res.data().uid)
        .onSnapshot(function(query) {
            query.forEach((doc) =>  {
                const { 
                    ...
                    date_created
                    } = doc.data();

        
                    followingPosts.push({
                        ...
                        date_created
                    });
                
            }) <----------- I put it in the on snapshot, instead of after. 

            followingPosts.sort(function(a,b){ 

                return b.date_created.toDate() - a.date_created.toDate()
        
            })
        
        });

    });

Thanks everyone

Upvotes: 1

Related Questions