Home > Enterprise >  array output in console and when displayed on page are different
array output in console and when displayed on page are different

Time:02-02

I'm fetching data from firebase which is structured in collection.subcollection.collection.document format.

let datesArr = [];
( () =>
{
  setTimeout( () =>
  {
    for ( let email of userEmail )
    {
      db.collection( `appointments/${ email }/details` ).onSnapshot( ( querySnapshot ) =>
      {
        querySnapshot.forEach( ( doc ) =>
        {
          let newDate = new Date (doc.data().dateInMills.at(-1) * 1000)

          datesArr.push( newDate  )
          datesArr.sort( ( a, b ) =>
          {
            return b - a
          })
          console.log( datesArr )
          scheduleTableRows.innerHTML  = `<div><div class='flex flex-col'>${ datesArr.at(-1) }</div></div>`
        } )
      } )
    }
  }, 1000 )
} )()

BREAKDOWN

  1. setTimeout is used since the name of the users are fetched from a different function which loads when dom is loaded and it takes a while to populate the array that stores the names.

  2. Date in the Db is stored in milliseconds and string format.

  3. Dates are then converted and pushed in array (datesArr) so that it can be sorted based on dates.

  4. After array is sorted, the dates are displayed on the page where the closest date is shown first and later dates follows.

ISSUE When I console log the datesArr, it shows the dates in the right order as desired but when I display the content of the array on the page its not the same, screenshots -

This is the output in the console, however it logs 10 arrays, which I don't why is happening.

Console

This is how the content of the array is displayed on the page

Browser

CodePudding user response:

It is displaying 10 but is maxing out at nine because of the common rule of arrays where the first one is zero and continues to be one less during the process. To change this, you can create variables or a loop for each where they add one. Sincerily, me

CodePudding user response:

The way you're displaying the dates inside the loop won't work properly. You add a date, sort all the dates, then add the most recent date to the HTML. If the date you just added isn't the most recent, you'll just show the same date as the previous iteration.

You should put all the dates into the array, then sort it, then display all of them.

let datesArr = [];
setTimeout(() => {
  let html = '';
  for (let email of userEmail) {
    db.collection(`appointments/${ email }/details`).onSnapshot((querySnapshot) => {
      datesArr = [...querySnapshot].map(doc => doc.data().dateInMills.at(-1) * 1000);
      datesArr.sort((a, b) => {
        return b - a
      });
      html  = datesArr.map(item => `<div><div class='flex flex-col'>${item}</div></div>`).join('');
    });
  }
  scheduleTableRows.innerHTML  = html;
}, 1000);

  • Related