Powering Statistics with Firebase Data

I have a Firebase resource connected that connects my Firestore Data to Retool. The query is pretty simple that I am using:

Get all the users under the "users" collection.

Now the problem I'm facing is further using this data under a statistics component where I want to count the number of users who joined in the last 24 hours.

My current statistic value setup, which gives back errors is something as follows:

{{
  let count = 0;
  let currentDate = new Date();
  let oneDayAgo = currentDate - 24 * 60 * 60 * 1000; // 24 hours in milliseconds

  getUsers.data.forEach((user) => {
    if (new Date(user.joinDate) >= oneDayAgo) {
      count++;
    }
  })

  // Output the count or do something with it
  return count;
}}

However this is not working and I've been trying to find resources to understand how this would work yet getting nowhere. Could really use the assistance on understanding how this would work.

Hi @bilalmotiwala - welcome to the community!

You may create JS query that performs the calculation of last 24 hours users count. This query may look like this:

const users = await getUsers.trigger()

// You need to replace 110 number with oneDayAgo calculation
const last24hoursUsers = users.filter(user => user.joinDate > 110);

const result = last24hoursUsers.length;

return result;

Then, in your statistics component, you will consume this query. Here's screenshot:

Hope this helps!

As I think of it, the better solution would be to modify your initial code with something like this:

{{ getUsers.data.filter(user => {
  let currentDate = new Date();
  let oneDayAgo = currentDate - 24 * 60 * 60 * 1000; 
  return user.joinDate > oneDayAgo
}).length}}

This code should be placed in the Value field of your Statistics component.

Click to see screenshot

This way is more efficient because there is no need in triggering getUsers query just for the sake of calculation.

Thanks a lot for the reply. I will definitely try both methods and see which works best and great to learn of the implementation methods supported :heart:

1 Like