2
votes

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.

2

2 Answers

6
votes

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
  })
})
3
votes
  const [todos, setTodos] = useState([]);

  useEffect(() => {
    db.collection('todo_collection')
      .orderBy('dateTime')
      .onSnapshot((snapshots) => {
        setTodos(snapshots.docs.map((doc) => doc.data()));
      });
  }, []);