Home > Enterprise >  ReactJS , Get data from Firebase order issue
ReactJS , Get data from Firebase order issue

Time:11-17

Get data from the firebase it's fine but when I send data I want that the last data is after the last item of the array but I don't know what is the default order but the order is not as I want like:

[a,b,bc] its data get from firebase when I send c and d its look like

[c,a,b,bc] or [c,a,d,b,bc] like what is the default order i did't understand

i want like:

[a,b,bc,c] or [a,b,bc,c,d]

Get data from firebase

 db.collection("messages").onSnapshot((snap) => {
      let messages = [];
      snap.docs.forEach((doc) => {
        messages.push({ ...doc.data(), id: doc.id });
      });
      console.log(messages);
      setmessge(messages);
    });

Send data into firebase

 const dataInput = {
      date_time: new Date().toLocaleString(),
      message,
      sender_id: userId,
    };
    db.collection("messages").add(dataInput);

CodePudding user response:

The Firebase documentation states clearly how the matching query documents are returned based on their ID ascending order:

By default, a query retrieves all documents that satisfy the query in ascending order by document ID.

You can specify an orderBy criteria on your collection references when retrieving data to get it sorted per the criteria:

db.collection("messages")
  .orderBy("date_time")
  .onSnapshot((snap) => {
    // ...   
});
  • Related