Obtaining a file from the Firebase database

After successfully implementing the login functionality in my app, I am now attempting to retrieve the user's document in order to display their name on the page.

email = loginemail.value;
    password = loginpassword.value;
    signInWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
            // Signed in 
            alert("Thanks for signing in!");
            const user = userCredential.user;
            
            useremail.innerHTML = user.uid;
            // ...
            })
        .catch((error) => {
            const errorCodelogin = error.code;
            const errorMessagelogin = error.message;
            createUserWithEmailAndPassword(auth, email, password)
            .then((userCredential) => {
                alert("Looks like you're a new user - we created a new account for you!");
                const user = userCredential.user;
                // ...
            })
            .catch((error2) => {
                const errorCoderegister = error2.code;
                const errorMessageregister = error2.message;
                pagebody.innerHTML = errorMessagelogin + "<br /><br />" + errorMessageregister;
            });
        });         
        
    const docRef = doc(db, "users", useremail.innerHTML);
    const docSnap = await getDoc(docRef);

    if (docSnap.exists()) {
        console.log("Document data:", docSnap.data());
    } else {
        // doc.data() will be undefined in this case
        console.log("No such document!");
    }
    

I directly followed Firebase's documentation while using the const docRef, with my table name and doc id plugged in. However, an error is being displayed in the console:

Uncaught (in promise) FirebaseError: Invalid document reference. Document references must have an even number of segments, but users has 1.

Answer №1

Your code attempting to load the document is running before the sign-in process has finished.

To avoid this issue, make sure to `await` the result instead of using `then()`.

const userCredential = await signInWithEmailAndPassword(auth, email, password)
// User successfully signed in
alert("Thanks for signing in!");
const user = userCredential.user;

userEmail.innerHTML = user.uid;
    
const docRef = doc(db, "users", userEmail.innerHTML);
const docSnap = await getDoc(docRef);

if (docSnap.exists()) {
    console.log("Document data:", docSnap.data());
} else {
    // Document data will be undefined in this case
    console.log("No such document!");
}

As a general rule: try not to mix `await` and `then` in your code until you have a better understanding of asynchronous operations. For now, stick with one or the other, but not both.

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

Is client-side rendering the new trend, bypassing traditional server-side rendering?

I'm exploring the idea of rendering my pages on the client side to reduce server load and minimize traffic. Typically, the first request to the server requires it to render the requested page and then send it to the user. Once the user interacts with ...

Enable Row Editing with a Click in Material Table

Utilizing the material-table library, I am implementing a feature to enable table rows to be editable upon double-click. The goal is for clicking on a row to trigger the same action as clicking the edit button located in the actions column on the leftmost ...

Saving a picture to a document after retrieving it through an HTTP request in a Node application

I seem to be overlooking something obvious, but here's the issue - I am receiving a PNG from a Mapbox call with the intention of saving it to the file system and then serving it to the client. I have successfully made the call, received raw data as a ...

Unlocking the treasures of JSON data in JavaScriptDiscovering the secrets of extracting JSON

let info = { "@type": "Movie", "url": "/title/tt0443272/", "name": "Lincoln", "image": "https://m.media-amazon.com/images/M/MV5BMTQzNzczMDUyNV5BMl5BanBnXkFtZTcwNjM2ODEzOA ...

Button-operated lightbox image slider

I am currently developing a website on WAMP where users can store images and view them in a lightbox effect. I have successfully implemented the lightbox effect, but I am facing challenges with moving between images within the lightbox. <html> <? ...

What is the reason behind Angular's continued use of JSON for encoding requests? (specifically in $http and $httpParamSerializerJ

Is there a way to set Angular to automatically send requests as x-www-form-urlencoded instead of JSON by default? Angular version 1.4.5 I've tried the following code snippet but it doesn't seem to work: angular.module('APP').config( ...

Dealing with substantial ajax responses using JavaScript

Currently, I am in the process of developing a website that utilizes jQuery File Tree. However, there is an issue with the enormous size of the AJAX response from the server - 900 KB and containing approximately 70,000 'files' (which are not actu ...

Attempting to utilize JavaScript in order to reset a text input field

I'm having trouble clearing a text field using this function. The alert is working but the field remains unchanged. What could be the issue? This function is designed to work on any text field. <!DOCTYPE html> <html> <head> ...

Switch up Google Fusion URL using Jquery

Looking to modify Google Fusion query using jQuery, here is the code snippet: var fusionid= ""; function initMap() { var map = new google.maps.Map(document.getElementById('map-canvas'), { center: {lat: 28.3268, lng: 84.1855}, zoom: 7 } ...

Searching for particular information within an array of objects

Seeking guidance as a newbie on how to extract a specific object from an array. Here is an example of the Array I am dealing with: data { "orderid": 5, "orderdate": "testurl.com", "username": "chris", "email": "", "userinfo": [ ...

Is it necessary to include a promise in the test when utilizing Chai as Promised?

Documentation provided by Chai as Promised indicates the following: Note: when using promise assertions, either return the promise or notify(done) must be used. Examples from the site demonstrate this concept: return doSomethingAsync().should.eventua ...

Fastify Schema Failing to Validate Incoming Requests

Currently, our backend setup involves using Node.js and the Fastify framework. We have implemented a schema in satisfy to validate user input. Below is the schema defined in schema.ts: export const profileSchema = { type: 'object', properti ...

What if the v-on:click event is applied to the wrong element?

I'm attempting to manipulate the anchor tag with jQuery by changing its color when clicked, but I'm struggling to correctly target it. <a v-on:click="action($event)"> <span>entry 1</span> <span>entry 2</span> ...

I encountered an issue where my button's onClick function was not functioning properly with the clickable component

Here is my display I have a component(Product) that can be clicked. One of its children is also a button. However, when I click it, the Product's function runs. How can I make sure my button executes separately? <ProductForm> ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Steps to import an external script into a NextJS application and access it from the main bundle

I have encountered an issue while working with the mercadopago library. I need to load the mercadopago script file and create an instance of the MercadoPago object. However, nextJS loads the main bundle before including the mercadopago file, resulting in a ...

Passing slots to child components within a VueJS application - A helpful guide

Within my application, I frequently utilize a list and list_item component. To provide a general idea: contact_list.vue <template lang="pug"> .table .table-header.table-row .table-col Contact .table-col Info .tabl ...

Activate an asynchronous request within a dropdown menu that was loaded using ajax

Let me start by presenting a simplified version of my code: HTML : <form id="add"> <select id="cat"> <option selected value="">…</option> <option value="a">A</option> <option value="b"& ...

Struggling to incorporate blocks into Jade for Express. Encountering errors like "Max Stack Size Exceeded" and issues with setHeader

I am currently using Express along with a simple express-generator server that I created. My first task was to focus on creating the view layout and extending the index page, but unfortunately, I have encountered some challenges. Throughout my process, I& ...

Organize information by time intervals using JavaScript

I am currently facing an issue where I need to dynamically sort data from the server based on different fields. While sorting is working flawlessly for all fields, I am encountering a problem with the time slot field. The challenge lies in sorting the data ...