Retrieve TypeScript object after successful login with Firebase

I'm struggling with the code snippet below:

login = (email: string, senha: string): { nome: string, genero: string, foto: string;} => {
    this.fireAuth.signInWithEmailAndPassword(email, senha).then(res => {
        firebase.database().ref('Usuarios/' + res.uid).once('value', snapshot => {
            return {
                nome: snapshot.val().nome,
                genero: snapshot.val().genero,
                foto: snapshot.val().avatar
            };
        });
    });
}

After logging in to Firebase and fetching my information, I expect it to return an object. However, I am encountering an error stating that I need to return something if the function type is not 'void' or 'any'. Despite returning an object as required.

Any advice on how to resolve this issue?

Answer №1

Your understanding of async and promises needs some adjustments. There are a couple of solutions to correct it.

1 - You can return the promise and have the caller resolve it.

login = (email: string, password: string): Promise<{name: string, gender: string, photo: string}> => {
    return new Promise<{name: string, gender: string, photo: string}>((resolve, reject) => {
        this.fireAuth.signInWithEmailAndPassword(email, password).then(result => {
            firebase.database().ref('Users/' + result.uid).once('value', snapshot => {
                resolve({
                    name: snapshot.val().name,
                    gender: snapshot.val().gender,
                    photo: snapshot.val().avatar
                });
            });
        });
    });
}

2 - You can pass a callback function in the login method and execute it when the promise is fulfilled

login = (email: string, password: string, loginCallback: (name: string, gender: string, photo: string) => any) => {
    this.fireAuth.signInWithEmailAndPassword(email, password).then(result => {
        firebase.database().ref('Users/' + result.uid).once('value', snapshot => {
            loginCallback({
                name: snapshot.val().name,
                gender: snapshot.val().gender,
                photo: snapshot.val().avatar
            });
        });
    });
}

Edit: I reviewed the Firebase Documentation (https://firebase.google.com/docs/database/web/read-and-write#read_data_once), and found another mistake.

firebase.database().ref('Users/' + result.uid).once('value', snapshot => {

should be:

firebase.database().ref('Users/' + result.uid).once('value').then(snapshot => {

Answer №2

The function nested within once in your inner function doesn't return the login function itself, but an object instead. Make sure that the outermost function returns a promise.

Consider revising with the following code snippet:

login = (email: string, password: string): Promise<any> => {
    // Add return statement here
    return this.fireAuth.signInWithEmailAndPassword(email, password).then(res => {
        // Include return for database call 
        return firebase.database().ref('Users/' + res.uid).once('value', snapshot => {
            return {
                name: snapshot.val().name,
                gender: snapshot.val().gender,
                photo: snapshot.val().avatar
            };
        });
    });
}

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

Animating Text Changes with JavaScript and jQuery

In my HTML, I have an input type="text" element and I want to attach an event handler that triggers when the text is changed. The issue arises because this input's value is dynamically updated by another JavaScript function, causing the event handler ...

AngularJS: Implementing a toggle click function for a list of items within an iframe

Here's the workflow I'm dealing with: I have a collection of items, each having an ng-click event that triggers the display of an iframe below the clicked item. The process works like this: When clicking an item, a hidden div tag beneath it ap ...

Establishing a secure Firebase connection with several Node.js instances via an AWS/ALB load balancer and Nginx

Looking to establish a connection between Firebase and a Node setup deployed on AWS/Elastic Beanstalk. The architecture includes 1-4 Node servers operating behind an ALB load balancer and Nginx proxy. Because Firebase requires WSS protocol, the ALB is nece ...

What is the best way to set up the login page and logged-in homepage using Node, Express, and Passport with the "/" route?

I am currently in the process of developing an application using Node.js, Express.js, and Passport.js. My goal is to create a seamless user experience on the homepage where if you are not logged in, you will see a login form (with potential for additional ...

`There is a problem of callbacks executing twice upon loading AJAX content`

My webpage is loading content using the waypoints infinite scroller plugin. After the AJAX call successfully adds DOM elements, a callback function is triggered to reinitialize javascript functionalities such as carousels, buttons, and other animations. ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Exploring the World of Angular JS Services

Following the recommended practices, I am working on encapsulating my global functions into reusable factory services. In the provided code snippet, my objective is to execute a function that takes the string value of "Qprogress" from my JSON data, perform ...

Locate every instance where two arrays are compared in TypeScript

My goal is to search for matches in Object 2 where the _type corresponds to filterByCallTypeTitulo in Object 1, and then create a new array including all the matched information from Object 2. I attempted to achieve this using the filter() method and forE ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

Experiencing trouble accessing a property in TypeScript

While working on my Next.js project, I have encountered a specific issue related to selecting the Arabic language. The translation functions correctly and the text is successfully translated into Arabic. However, the layout does not switch from its default ...

Using template literals with Optional chaining in Javascript does not yield the expected results

Trying to implement template literal with optional chaining. type Item = { itemId:number, price: number}; type ItemType = { A:Item, B:Item }; const data : ItemType = { A:{itemId:1, price:2}, B:{itemId:2, price:3} }; let key = `data?.${variable}?.ite ...

Employing jQuery, how can one assign attributes to appended HTML and store them

So, I am currently working on a backend page for managing a blog. This page allows users to create, edit, and delete articles. When the user clicks the "edit" button for a specific article named 'foo', the following actions are performed: The ...

Is the Order of a JSON Array Dependable?

When working with JSON, it's clear that relying on the ordering of key-value pairs may not be reliable. For instance, a JSON parser could interpret { "someKey" : "someValue", "anotherKey" : "anotherValue", "evenAnotherKey" : "evenAnotherV ...

Trouble with Metro UI Library: CSS not loading properly

I am having trouble with the navbar CSS on my website while using the Metro UI CSS library. Check out my HTML code: <!DOCTYPE html> <html lang="en"> <head> <title>TelePrint Blog</title> <link rel="stylesheet" href= ...

Can someone help me extract a specific portion and display the dimensions of the area?

In order for the mouse to create a selection range, simply release the mouse after making your selection. The selected area will display the values of width and height on both the X-axis and Y-axis in the designated fields. I am facing this issue and woul ...

The error message received is: "mongoose TypeError: Schema is not defined as

Encountering a curious issue here. I have multiple mongoose models, and oddly enough, only one of them is throwing this error: TypeError: Schema is not a constructor This situation strikes me as quite odd because all my other schemas are functioning prop ...

Using Selenium WebDriver and JavaScript: Enabling Chrome to Download Multiple Files at Once

After scouring through multiple documents for hours like https://www.selenium.dev/documentation/en/webdriver/js_alerts_prompts_and_confirmations/ as well as https://chromedriver.chromium.org/capabilities and I was unsuccessful in finding a solution wit ...

Should tabs be closed or redirected after successful authentication with Google?

I have a project that was developed using perl-dancer and angular. The project is integrated with Google as an openID system. On some of the pages, there is an edit grid with a save button. To prevent loss of unsaved data when the session (created from pe ...

What sets xhr.response apart from xhr.responseText in XMLHttpRequest?

Is there any difference between the values returned by xhr.response and xhr.responseText in a 'GET' request? ...

How can we efficiently retrieve newly submitted JSON data using AJAX?

Is there an efficient way for a user to input a number, submit it, and have it update a JSON page without refreshing the entire webpage? Can this be achieved using an ajax call? The code below retrieves game data, but I want it to update when the user su ...