Ways to verify the uniqueness of usernames within Firebase

I have been working on a function to check if a username is unique in my Firebase database. Despite researching and implementing code, it doesn't seem to work as expected. Any assistance would be greatly appreciated - what am I missing?

 onChangeUsername = (event) => {

var oldError = {...this.state.error};

firebase.database().ref().child("Usernames").orderByValue().once('value', (snapshot) => {
  var exists = (snapshot.val() !== null);
  console.log(exists);
  console.log("hello");
});


if(this.state.validation.username.unique===true)
{oldError.username = "This username is already taken"}

else if((event.nativeEvent.text.length<this.state.validation.username.min) || (event.nativeEvent.text.length>this.state.validation.username.max) )
{oldError.username = "Username should be between " + this.state.validation.username.min + " and " + this.state.validation.username.max + " characters" ;}


else oldError.username = "";



this.setState({ username: event.nativeEvent.text, error:oldError })
}

Here is the structure of my database:

Database:{ Usernames: {uid1: username1, uid2: username2}}

****Question Update **** After Feedback from Frank, I have made some changes to my code. However, it still doesn't produce the desired result. He pointed out some errors that needed correction:

onChangeUsername = (event) => {

    var oldError = {...this.state.error};

    firebase.database().ref().child("Usernames").orderByKey().equalTo("Username1").once('value', (snapshot) => {
      var exists = (snapshot.val() !== null);
      console.log(exists);
      console.log("hello");
    });


    if(this.state.validation.username.unique===true)
    {oldError.username = "This username is already taken"}

    else if((event.nativeEvent.text.length<this.state.validation.username.min) || (event.nativeEvent.text.length>this.state.validation.username.max) )
    {oldError.username = "Username should be between " + this.state.validation.username.min + " and " + this.state.validation.username.max + " characters" ;}


    else oldError.username = "";



    this.setState({ username: event.nativeEvent.text, error:oldError })
  }

and my current database setup looks like this:

Database:{ Usernames: {Username1: uid1, Username2: uid2}}

Answer №1

Your query is missing a comparison:

firebase.database().ref().child("Usernames").equalTo("Username1").orderByValue()

To optimize your data structure, I suggest flipping it around. Use user names as keys in the parent node to ensure uniqueness:

Database:{ 
  Usernames: {
    Username1: uidOfUserWithUsername1, 
    Username2: uidOfUserWithUsername2 
  }
}

This change will simplify and speed up your lookups without the need for queries. It also enables easy access to additional information about users associated with specific user names.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The render function is not being executed due to a disruption in the code flow

Within the given code snippet, there is a peculiar issue with the render function being called inside the loop below. Strangely, the console.log statement before the function call executes successfully, but the one directly inside the function does not s ...

Learn the technique of invoking a sub component's method from the parent component in Vue.js

I am looking to trigger a method in a sub component from the parent component in Vue.js in order to refresh certain parts of the sub component. Below is an example showcasing what I aim to achieve. Home.vue <template> <componentp></compo ...

Simultaneously sort and modify values within an array

I am working with an array where the first number in each sub-array indicates the order. Whenever I change the order, I need to rearrange the array and re-index it starting from 2, 3, 4, 5. const payments = [ [2, paymentName1, '5%'], [3, ...

Altering the URL of Nuxt assets in the generated HTML documents

My goal is to create a static website using Nuxt, but I want it to function without the need for a server, simply by opening the HTML files in a browser. One issue I am encountering relates to the URLs of the assets imported within the HTML files. I requir ...

Transferring information from a function-based module to a higher-level class component in React Native

I'm currently working on an application that has a tab navigation. One of the screens in the tab is called "ScanScreen," where I'm trying to scan a UPC number and send it to the "HomeScreen" tab, where there's a search bar. The goal is for t ...

A see-through object appears only properly when viewed from one specific angle

I am currently working with THREE.js and the WebGL renderer, facing an issue with a self-transparent object in my scene. This object is composed of a single geometry with a basic material that includes a texture and has the transparent: true property enabl ...

Utilizing Angular 10 to Transform a JSON Data into a Custom String for HTML Rendering

I have received a JSON response from my backend built using Spring Boot. The "category" field in the response can either be 1 or 2, where 1 represents Notifications and 2 represents FAQs. { "pageNumber": 0, "size": 5, "totalPages&q ...

Ways to verify whether a user is not defined

My code includes a command that sends a Direct Message to a user, with the user being specified as follows: let user; if (message.mentions.users.first()) { user = message.mentions.users.first(); } else if (args[0]) { user = message. ...

Transform JSON headers and rows into Object keys using Node.js

I am currently working on retrieving data from an API in JSON format using Node JS. The JSON data consists of headers and rows, including information such as "Vendor, Price, SKU, Error" (see the attached screenshot). I am looking to structure this data int ...

I am looking to obtain an associative array from a collection of JavaScript objects

Here is a JavaScript object that I need help transforming: <pre> { 1:{taxCalculation: 39.95, taxId: "3"}, 2:{taxCalculation: 10, taxId: "3"}, 5:{taxCalculation: 0.48, taxId: "2"} } </pre> My goal is to convert this object into an assoc ...

Is it time to execute a mocha test?

Good day, I am currently exploring the world of software testing and recently installed Mocha. However, I seem to be encountering an issue with running a basic test that involves comparing two numbers. Can someone please guide me on why this is happening a ...

Can you assign a particular symbol to a function for naming variables?

When incorporating a new function into jQuery: $.fn.boxLoader = function() { var FilterSelect = ($("[id^='filter_a_selector_']")); // perform actions on FilterSelect return this; }); Then, when a par ...

Troubleshooting: AngularJS not retrieving values from hidden input fields in ASP.NET MVC

I'm working on passing a list to a view as a hidden type and retrieving those values using Angular. for(int i = 0; i < Model.ListOfIds.Count;i++) { <input type="hidden" ng-model="model.ManagersId" value="@Model.ListOfIds[i]" /> / ...

"Using Jest to specifically test the functionality of returning strings within an object

Attempting to run a jest test, it seemed like the issue was with the expect, toBe section as I believed that the two objects being compared (data, geonames) were exactly the same. However, upon closer inspection, they turned out to be different. The struct ...

VueJS error: 'Property or method is not defined on the instance' message appears despite the method being defined on the instance

Is there a way in Vue.js to dynamically assign the class 'adjust' based on the value of a computed property called "isTrueSet"? I keep encountering the following error message: [Vue warn]: Property or method "itTrueSet" is not defined on the inst ...

Discovering the potential of utilizing an array transmitted by Node/Express on the server-side and integrating it into Google Maps on the client-side

When attempting to set up clustering markers on Google Maps, I encountered a challenge. Client-Side <script> // Code snippet from Google Map docs function initMap() { // Array of locations const locations = [ { lat: -31.56391, lng: 147.15 ...

Navigating Through Different Environments in Your React Application

Currently, I am tackling a small project where I am utilizing React for the frontend and Java for the backend. The project involves two distinct environments. My main struggle revolves around effectively managing multiple environments. To set the API URL, ...

Execute JavaScript function after the window has finished loading, regardless of any asynchronous downloads

In my app, there is an initialise function that I want to execute only when two conditions are met: first, the window has finished loading ($(window).load()), and second, Typekit has loaded. $(window).load(function() { try { Typekit.load({ act ...

Setting breakpoints in Node-Inspector can be quite challenging

After successfully setting up a web application, I decided it was time to learn how to properly debug it without relying on console.log. To start, I ran Node-Inspector via node-debug server.js (the main script file) and attempted to set up a breakpoint wit ...

What is the best way to save the raw text or event-stream data from a JavaScript get request when the server is continuously loading?

Currently, I'm attempting to fetch some basic data from an API. Here is the URL for the request: The issue lies in the fact that the server appears to keep refreshing the page constantly. This endless loading occurs both when using a browser and with ...