0

Here Is My Main Code:

function show_users_posts() {
  document.getElementById('post-spinner').style.display= "none"
    var timestampfinal

    const database = firebase.database()
    database.ref('Cloud/Accounts/' + myParam + '/Posts')
      .orderByChild('sortDate')
      .limitToLast(10) // get 10 most recent entries
      .once('value', function (snapshot) { // <-- consider Promise API instead
        const sortedChildren = [];
        snapshot.forEach(childSnapshot => { sortedChildren.unshift(childSnapshot) }); // reverses the order

        sortedChildren.forEach(childSnapshot => {
          const childKey = childSnapshot.key;
          const childData = childSnapshot.val();

          /* rest of the code */

          var description = childData.Description
          var image = childData.Thumbnail
          var link = childData.Link
          var seconds = childData.Seconds
          var created = parseInt(seconds)
          // The time now
          var now = new Date().getTime();

          // The difference between now and created
          var howLongAgo = created - now;

          // Convert to a positive integer
          var time = Math.abs(howLongAgo);

          // Define humanTime and units
          var humanTime, units;

          // If there are years
          if (time > (1000 * 60 * 60 * 24 * 365)) {
            humanTime = parseInt(time / (1000 * 60 * 60 * 24 * 365), 10);
            units = 'years';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          // If there are months
          else if (time > (1000 * 60 * 60 * 24 * 30)) {
            humanTime = parseInt(time / (1000 * 60 * 60 * 24 * 30), 10);
            units = 'months';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          // If there are weeks
          else if (time > (1000 * 60 * 60 * 24 * 7)) {
            humanTime = parseInt(time / (1000 * 60 * 60 * 24 * 7), 10);
            units = 'weeks';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          // If there are days
          else if (time > (1000 * 60 * 60 * 24)) {
            humanTime = parseInt(time / (1000 * 60 * 60 * 24), 10);
            units = 'days';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          // If there are hours
          else if (time > (1000 * 60 * 60)) {
            humanTime = parseInt(time / (1000 * 60 * 60), 10);
            units = 'hours';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          // If there are minutes
          else if (time > (1000 * 60)) {
            humanTime = parseInt(time / (1000 * 60), 10);
            units = 'minutes';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          // Otherwise, use seconds
          else {
            humanTime = parseInt(time / (1000), 10);
            units = 'seconds';
            timestampfinal = humanTime + ' ' + units + ' ago'
          }

          console.log(timestampfinal)
          
          //childKey
          //childData.FirstName
      

          var html = `<div class="col">`;
          html += `<div class="card h-100">`;
          if (image == "") {
            html += `<img height="300px" width="150px" src="img/No-Image-Placeholder.svg.png" class="card-img-top" alt="...">`;
          }
          else {
            html += `<img src="${image}" class="card-img-top" alt="...">`;
          }
          
          html += `<div class="card-body">`;
          if (verificationstatusforuser == "Verified") {
            html += `<h4 class="card-title">${myParam}<i class="material-icons" style="color: #458eff">verified</i></h5>`;
          }
          else if (verificationstatusforuser == "Owner") {
            html += `<h4 class="card-title">${myParam}<i class="material-icons" style="color: #458eff">verified_user</i></h5>`;
          }
          else if (verificationstatusforuser == "Domain") {
            html += `<h4 class="card-title">${myParam}<i class="material-icons" style="color: #458eff">domain</i></h5>`;
          }
          else if (verificationstatusforuser = "False") {
            html += `<h4 class="card-title">${myParam}</h5>`;
          }
          
          html += `<p class="card-text">${description}</p>`;
          if (link == "") {
            
          }
          else {
            html += `<a href="${link}" target="_blank" type="button" class="btn btn-dark">Open Attached Link</a>`;
          }
          
          html += `</div>`;
          html += `<div class="card-footer">`;
          html += `<small class="text-muted">${timestampfinal}</small>`;
          html += `</div>`;
          html += `</div>`;
          html += `</div>`;
          
          document.getElementById('post-section').innerHTML += html;
        })
      });
    
    
}
        //And The Code Continues, But This is the main part i wanna fix

Here is my Firebase Data Tree:

"Cloud": {
    "Accounts": {
        "User1": {
            "Posts": {
                "1-31-2022-1643620733159": {
                    "sortDate": 1643620733159,
                }
                "1-31-2022-1643620742152": {
                    "sortDate": 1643620742152,
                }
            }
        }
    }
}

Now All I Want To Do is reverse the order making the most recent posts on top and the oldest on bottom, but the code im using doesnt even change the order, and i dont know why, iv tried order by Key, Iv tried everything, nothing is working, The Reference Is Correct Because It Loads All My Posts But Not In The Right Order

Edited Code - adding the log to console:

var database = firebase.database()
    database.ref('Cloud/Accounts/' + myParam + '/Posts').orderByChild('sortDate').once('value', function (snapshot) {
    
      snapshot.forEach(function(childSnapshot) {
        var childKey = childSnapshot.key;
        var childData = childSnapshot.val();
        console.log(childData.sortDate);

Logs This:

1643620733159

1643620742152

It Logs Each Value, But I Need It The Other Way Around.

Ethan Marr
  • 49
  • 7
  • That was one of the posts I have check and it didn’t work sadly – Ethan Marr Jan 31 '22 at 10:48
  • 1
    Does this answer your question? [Attempt to sort firebase database is not working](https://stackoverflow.com/questions/53016592/attempt-to-sort-firebase-database-is-not-working) – Kundan Jan 31 '22 at 12:03
  • That post states it needs to be in milliseconds, i already have my time stamp I’m trying to sort by in Milliseconds, but for some reason it still puts it in the wrong order, unless there’s a way to reverse the array on the client side – Ethan Marr Jan 31 '22 at 13:39
  • 1
    The code in your question looks fine to me at first glance, and seems to match the JSON data. Can you change the code to log the `sortDate` value inside the loop, and then edit your question to show the updated code and its output? – Frank van Puffelen Jan 31 '22 at 15:29
  • Yes I can, just give me about 40 minutes, I have to do a few things before I get back to work on this project – Ethan Marr Jan 31 '22 at 16:11
  • I Updated My Code With The Output Values – Ethan Marr Jan 31 '22 at 18:37

1 Answers1

2

As covered in the post I linked to this question, you must either:

  • Add a child property with the inverted timestamp. (a negative sortDate)
  • Read the children in ascending order and then invert them on the client. (shown below)
const database = firebase.database()
database.ref('Cloud/Accounts/' + myParam + '/Posts')
  .orderByChild('sortDate')
  .limitToLast(10) // get 10 most recent entries
  .once('value', function (snapshot) { // <-- consider Promise API instead
    const sortedChildren = [];
    snapshot.forEach(childSnapshot => { sortedChildren.unshift(childSnapshot) }); // reverses the order

    sortedChildren.forEach(childSnapshot => {
      const childKey = childSnapshot.key;
      const childData = childSnapshot.val();

      /* rest of the code */
    })
  });
samthecodingman
  • 23,122
  • 4
  • 30
  • 54
  • Hey It Sorta Works Now, But It Only Displays 1 Of 2 Posts, I Want It To Show All The Posts, Its Only Showing The Most Recent One, I Made Over 20 Posts To It, And Its Only Showing The Most Recent One – Ethan Marr Jan 31 '22 at 22:36
  • I dont know what to do :/ i got closer but hit another bump @samthecodingman – Ethan Marr Jan 31 '22 at 22:58
  • 1
    @EthanMarr Ah, I forgot that `forEach` will terminate the loop if the callback returns a truthy value. Adding the braces to the callback should prevent that. Also, there is no need to tag a user on their own post, we get notifications for it anyway. Also don't forget StackOverflow is run by volunteers, be patient waiting for responses as we have other things to do too. – samthecodingman Jan 31 '22 at 23:27
  • Im Sorry I Am Very New To Stack Overflow, And Programming, Could You Show Me A Code Example With That Just So I Dont Mess It Up – Ethan Marr Jan 31 '22 at 23:29
  • 1
    @EthanMarr the post has been edited with the updated code already. You can click the "[edited X Y ago](https://stackoverflow.com/posts/70933298/revisions)" link to see recent changes. – samthecodingman Jan 31 '22 at 23:29
  • I Added The Updated Code, But Now Its Unsorted Again? – Ethan Marr Jan 31 '22 at 23:32
  • 1
    @EthanMarr It shouldn't be. I'm guessing that you still have `snapshot.forEach(childSnapshot =>` in your code by accident. Delete what you have, copy in the above code, and then carefully add your original code back in. – samthecodingman Jan 31 '22 at 23:36
  • I Redid everything, and it still is showing stuff in the wrong order, i was gonna paste my new code in the post but it wont let me edit – Ethan Marr Jan 31 '22 at 23:42
  • I Added All The Code Im Using For My Function, Even Updated It With Your Answer, Its Back To Displaying All The Snapshots in a descending order, not newest to oldest, i dont know why – Ethan Marr Feb 01 '22 at 00:13
  • 1
    @EthanMarr Each `

    ` is paired off with ``. That'd probably cause the HTML to freak out. It's also good form to close off your image tags (``). Once you fix those things, it should work as expected.

    – samthecodingman Feb 01 '22 at 06:43
  • I actually figured it out a different way, I was tweakin around with the code, and I noticed it was going from smallest down to lowest in the database, so then I managed to make a counter in the for each function, with a global variable, adding to the global variable, and then when I submit a post, I made the childKey in the database that global variable, so it got sorted automatically, I appreciate your guy’s help I’ll close the form now, I’ll mark it done – Ethan Marr Feb 01 '22 at 15:14