How to orderByValue onSnapshot using Firestore

2019-07-09 03:44发布

In componentWillMount I am registering an onSnapshot function which updates the state.

componentWillMount () {
    todoRef.onSnapshot((doc) => {
      let todos = []
      doc.forEach(doc => {todos.push(doc.data())})
      this.setState({
        todos
      })
    })
  }

However, the way that firebase/firestore works is that it just pushes up random keys, so when I get the data back it's not in the correct order.

I know there is a .orderByValue() function but I've tried implementing it and can't seem to figure it out.

1条回答
唯我独甜
2楼-- · 2019-07-09 04:04

My ref was const todoRef = db.collection("todos");

So once you've got the reference to your collection, you can then do the sort query.

todoRef.orderBy('createdAt').onSnapshot((docSnapShot) => {
  let todos = []
  docSnapShot.forEach(doc => {todos.push(doc.data())})
  this.setState({
    todos
  })
})
查看更多
登录 后发表回答