2

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.

3
  • What's the output of followingPosts just before you run sort over it? I'm just checking to make sure there are in fact elements within it. I'm not sure what the error you're getting is, whether it's empty or you get data that isn't in order. Commented Jan 12, 2021 at 1:37
  • @MichaelBauer Ahh, I think you are on to something here. I added console.log(followingPosts) AFTER the call to firestore, before I set the state, and it outputted Array []. I can think of only one thing: the query to firestore is asynchronous, so it does not sort the array because it is blank. But that doesn't explain why it didn't work when I added the sorting within the querysnapshot Commented Jan 12, 2021 at 1:42
  • @MichaelBauer solved the problem, added answer. Your comments helped!! thanks Commented Jan 12, 2021 at 1:55

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

also, doing a.date_created - b.date_created sorts it in an ascending order. d.date_created - a.date_created sorts it in a descending order.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.