Skip to content Skip to sidebar Skip to footer

Firebase Get All Usernames & User Id Starting With User Entered Character

I am trying to only fetch username and user IDs that only start with the User entered text. Below is my firebase database: As you can see the database contains a list of user Ids

Solution 1:

Firebase Database queries do a prefix match, not a contains. But since you only specify startAt(...) the query matches all users from the ones whose name starts with the prefix, including all names after it. If you only want results that start with the prefix string, you'll want to also use endAt(...):

const query = ref.orderByChild('username').startAt(action.searchText)endA‌t(action.searchText+‌​"\uf8ff");
const snapshot = yield call([query, query.once], 'value');
snapshot.forEach(function(child) { 
  console.log(child.key, child.val().username);
});

Solution 2:

Initially, I was thinking the equalTo() query along with Firebase .indexOn the username.

However, what we really need is a substring like ECMAScript 6's String.prototype.startsWith() method:

.startsWith(inputValue);

So, The only way I see to do it with realtime DB is to get/fetch/.once it then process client side where you have more robust string matching capability. I guess the next question is how to pull/fetch only the username property of each user key.


Solution 3:

To query based on the first character, you should get that character and pass it to the startAt() function:

const query = ref.orderByChild('username').startAt(action.searchText.charAt(0));

Post a Comment for "Firebase Get All Usernames & User Id Starting With User Entered Character"