Home > Net >  Why Firebase query with orderByChild returns a link?
Why Firebase query with orderByChild returns a link?

Time:06-30

According to the enter image description here

Am I missing something?

Thanks!

CodePudding user response:

Your playersByPoints here is a Query object, which when logged returns the string of the linked database reference.

You need to actually invoke the query using either get(q) or onValue(q) to get the data you are looking for.

// one-off
const playersByPointsQuery = query(
  ref(db, 'usersPoints'),
  orderByChild('points'),
);

const playersByPointsQuerySnapshot = await get(playersByPointsQuery);
const playersByPoints = [];
      
playersByPointsQuerySnapshot.forEach(childSnapshot => {
  playersByPoints.push({
    ...childSnapshot.val(),
    _key: childSnapshot.key
  });
});

// todo: do something with playersByPoints

or

// realtime listener
const playersByPointsQuery = query(
  ref(db, 'usersPoints'),
  orderByChild('points'),
);

const unsubscribe = onValue(
  playersByPointsQuery,
  {
    next: (playersByPointsQuerySnapshot) => {
      // new data available
      const playersByPoints = [];
      
      playersByPointsQuerySnapshot.forEach(childSnapshot => {
        playersByPoints.push({
          ...childSnapshot.val(),
          _key: childSnapshot.key
        });
      });
    
      // todo: do something with playersByPoints
    },
    error: (err) => {
      // error
      // todo: handle
    }
  }
);
  • Related