0

I have a problem with GiftedChat, the messages appear completely disorganized in the app and even looking for messages directly from the firebase (where it is correct), the app does not get a logical order. When sending is organized, however the problem is when you load the messages. I'm completely lost

loadMessages = async () => {
        const { user } = this.props;
        const matchId = this.props.navigation.getParam('matchId');
        const data = (await firebase.database().ref(`matchs/${matchId}/messages`).limitToLast(300).once('value')).val();

        let messages = [];
        if(data){
          Object.keys(data)
            .forEach(messageId => {
              let message = data[messageId];

              if(_.get(message, 'user._id') !== user.uid) _.push(message);
              messages.push(message);

            });
        }


        this.setState(() => ({
          messages,
        }));

      }

My JSON:

{
  "-LkAMYoS3fySk46Pbpan" : {
    "_id" : "f5ba3d9a-c346-4f79-b371-c5d54798567e",
    "createdAt" : 1563558815857,
    "text" : "First message",
    "user" : {
      "_id" : "BVY4MDwSaaSDI2bAGjwkZlYktsK2",
      "avatar" : "https://firebasestorage.googleapis.com/v0/b/wefound-760f2.appspot.com/o/users%2FBVY4MDwSaaSDI2bAGjwkZlYktsK2%2Fphotos%2Fk1xuqv26wdrjxoxmp8m.jpg?alt=media&token=7c16a0e4-2cb8-45a5-83a4-635d49c71180",
      "name" : "Rafael"
    }
  },
  "-LkAMZiITDxHE1WfCBGC" : {
    "_id" : "c2755b48-136d-4a68-b283-377ebac7df8e",
    "createdAt" : 1563558819564,
    "text" : "Second message",
    "user" : {
      "_id" : "BVY4MDwSaaSDI2bAGjwkZlYktsK2",
      "avatar" : "https://firebasestorage.googleapis.com/v0/b/wefound-760f2.appspot.com/o/users%2FBVY4MDwSaaSDI2bAGjwkZlYktsK2%2Fphotos%2Fk1xuqv26wdrjxoxmp8m.jpg?alt=media&token=7c16a0e4-2cb8-45a5-83a4-635d49c71180",
      "name" : "Rafael"
    }
  },
  "-LkAM_l4o_w_QeCsYRc8" : {
    "_id" : "65772152-afd9-4353-b752-ac65978a536d",
    "createdAt" : 1563558823838,
    "text" : "Third message",
    "user" : {
      "_id" : "BVY4MDwSaaSDI2bAGjwkZlYktsK2",
      "avatar" : "https://firebasestorage.googleapis.com/v0/b/wefound-760f2.appspot.com/o/users%2FBVY4MDwSaaSDI2bAGjwkZlYktsK2%2Fphotos%2Fk1xuqv26wdrjxoxmp8m.jpg?alt=media&token=7c16a0e4-2cb8-45a5-83a4-635d49c71180",
      "name" : "Rafael"
    }
  },
  "-LkAMcSSTOP7L1CwyiU4" : {
    "_id" : "e69f3a72-0f4e-4c06-a763-518ef1984aa0",
    "createdAt" : 1563558834859,
    "text" : "Fourth message",
    "user" : {
      "_id" : "BVY4MDwSaaSDI2bAGjwkZlYktsK2",
      "avatar" : "https://firebasestorage.googleapis.com/v0/b/wefound-760f2.appspot.com/o/users%2FBVY4MDwSaaSDI2bAGjwkZlYktsK2%2Fphotos%2Fk1xuqv26wdrjxoxmp8m.jpg?alt=media&token=7c16a0e4-2cb8-45a5-83a4-635d49c71180",
      "name" : "Rafael"
    }
  },
  "-LkAMduvBrEnUG6POGKt" : {
    "_id" : "897b2042-25dc-46ec-a5f3-5bdc1fc355dd",
    "createdAt" : 1563558840853,
    "text" : "Fifth message",
    "user" : {
      "_id" : "BVY4MDwSaaSDI2bAGjwkZlYktsK2",
      "avatar" : "https://firebasestorage.googleapis.com/v0/b/wefound-760f2.appspot.com/o/users%2FBVY4MDwSaaSDI2bAGjwkZlYktsK2%2Fphotos%2Fk1xuqv26wdrjxoxmp8m.jpg?alt=media&token=7c16a0e4-2cb8-45a5-83a4-635d49c71180",
      "name" : "Rafael"
    }
  }
}

enter image description here

I gave console.tron.log () in the messages and they appear disorganized exactly the same is in the app, the problem is in the component?

1 - refers to the function that loads the messages.

2 - JSON file

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • My chat is completely disorganized and even seeking the information straight from the firebase (in the firebase is correct) in the app appears in an order totally without any logic – Rafael La Guardia Jul 20 '19 at 13:55
  • 1
    Don't post pictures of code please. Instead post the code as text, and use the formatting options of Stack Overflow to mark up it. You can click the `edit` link under your question to make these changes, and to add any other information to your question. – Frank van Puffelen Jul 20 '19 at 13:56
  • Frank van Puffelen. Okay, thanks for letting me know, welcome to the new journey, it's less than 1 year old and any input is welcome – Rafael La Guardia Jul 20 '19 at 14:13
  • Can you add a snippet of the JSON that you're reading here (as text, no screenshots please)? You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Jul 20 '19 at 14:25

2 Answers2

0

There are two steps to ordering the data:

  1. Telling the Firebase Database server to return the child nodes in the correct order.
  2. Maintaining that order in your client-side code.

As far as I can tell your code does neither of these, which means the nodes end up in whatever order your client uses for JSON properties (which are by definition unordered).

Let's first see how to retrieve the data in the correct order from Firebase:

const snapshot = (await firebase.database().ref(`matchs/${matchId}/messages`).orderByChild('createdAt').limitToLast(300).once('value'));

The above orders all child nodes by the value of their createdAt property, then returns the last 300 in order to the client.

You'll note that I don't call val() here yet. The reason for that is that snapshot.val() returns a JSON object, and properties in a JSON object have no defined order. So if you call .val() too early, you lose the ordering information that the server returned.

Next up is processing them in the client-side code to not lose that order, which depends on using DataSnapshot.forEach():

data.forEach((message) => {
  messages.push(message.val());
})
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • and if I wanted to get the firebase in descending order? – Rafael La Guardia Jul 20 '19 at 20:06
  • The Firebase Database can only return ascending results, so you will either have to reverse them client-side or store an inverted value in the data and order on that. Note that this is a different/additional question, and has been covered before. See https://stackoverflow.com/questions/44442816/firebase-date-order-reverse, https://stackoverflow.com/a/25613337, – Frank van Puffelen Jul 20 '19 at 21:51
0

Finally, I am able to solve this problem by sorting the JSON which is coming to from the server based on the date and time(CreatedAT). If the JSON data stored in a variable called discussion then your code should be

      discussion.sort(function compare(a, b) {
        var dateA = new Date(a.createdAt);
        var dateB = new Date(b.createdAt);
        return dateB - dateA;
      });  

In your case, data or messages is the one which holds the JSON. Add this code once you get the code in JSON format.

Thank you.

Deepak N
  • 1,408
  • 3
  • 15
  • 37