Home > front end >  How can i order a snapshot value in timestamp order?
How can i order a snapshot value in timestamp order?

Time:02-26

I want to show the posts in the feed by the date it was posted, I am currently showing them by the user and that is very confusing, I would like it better if it was showing the posts by the date the post was created, I am using Firebase and Vue.js v2

I know firebase stores a timestamp automatically so I am looking for a way to order the posts by that time stamp regardless of the user order, is it still posible?

here is the code I am using to fetch the data from Firebase and the code on the component.

    <template>
    <div>
           <div
           v-for="post in allPosts.slice().reverse()"
           :key="post._key">
           <v-card >
           <v-row no-gutters>
           <v-col cols="1">
           <v-img
           
           width="30"
           :src="post.photoURL">
           </v-img>
           </v-col>
           <v-col cols="10">
             <p >{{post.postText}}</p>
             <p >{{post.displayName}}</p>
             </v-col>
             </v-row>
       </v-card>
     </div>
   </div>
</template>
<script>
import firebase from '@/plugins/firebase'

let db = firebase.database();
//let usersRef = db.ref('users');
let postRef = db.ref('posts');

export default {
  name: 'FintechSocialFeed',
  data: () => ({
  authUser: null,
  allPosts: [] // initialise an array
}),
  methods: {
  },
  created: function() {
    data => console.log(data.user, data.credential.accessToken)
    firebase.auth().onAuthStateChanged(user => {
        if (user) {
          postRef.on('value', snapshot => {
            const val = snapshot.val()
            if (val) {
              this.allPosts = Object.values(val).flatMap(posts =>
              Object.entries(posts).map(([ _key, post ]) => ({ _key, ...post})))
            }
            console.log(snapshot.val())
          });
        }

     })
   }
}
</script>

here is a little image of how it looks, first is Abraham's posts then the jake's so I want it to be by date not by user order.

enter image description here

CodePudding user response:

Firestore can only order/filter data on values that it has indexes for. While it may also store additional metadata for its own purposes, this values are typically not indexed (the document ID being the one exception to that), and thus can't be used in queries.

Thus there is no way to order Firestore results based on the internal timestamp. If you want to be able to order documents on a timestamp, you'll have to store that timestamp as a field in the document, and then pass that field name to orderBy.

  • Related