Does the onAuthStateChanged listener in firebase trigger immediately upon user login or logout?

//initialize auth change listener
useEffect(() => {
    auth.onAuthStateChanged((user) => {
        if (user) {
            router.replace('/')
        }
    })
    setInitializing(false)
}, [])

//*handled by login button
const login = async (e: any) => {
    e.preventDefault()

    if (!form.email || !form.password) {
        setError('Email Id and Password not found')
        return
    }
    try {
        await signInWithEmailAndPassword(auth, form.email, form.password)
        const idToken = await getIdToken()

        //if userId and password is wrong
        //return with an error
        if (!idToken) {
            setError('Invalid User')
            await signOut(auth)
            return
        }

        //retrieve user data from firestore
        const _getUser = await getUser(idToken!)

        //if no user found
        //return with an error
        if (_getUser.error) {
            alert(_getUser.error)
            setError(_getUser.error)
            await signOut(auth)
            return
        }

        //if user is found
        //store jwt token in cookie
        document.cookie = `{"jwt":${_getUser.jwt}}`
    } catch (e: any) {
        // console.log(e.message);
    }
}

Summary-> useEffect starts the onAuthStateChanged listener to redirect the user to the homepage if authenticated.

Login function attempts to sign in the user with email and password using signInWithEmailAndPassword().

After completing necessary tasks, the function sets the document.cookie = 'boo:foo' at the end.

Question-> The onAuthStateChanged doesn't redirect the user to the homepage instantly after a successful sign in. Instead, it waits for the login function to complete or the document.cookie to be set. Why does this delay occur?

Framework used: NEXT JS

Language: Typescript

Answer №1

Within the realm of JavaScript, it operates as a language that is inherently single-threaded. This means that the execution of your onAuthStateChanged handler may be delayed until after your login function completes its synchronous tasks.

To prevent the blocking of the handler, you have the option to encapsulate the code that should not hinder the handler in a specific block:

setTimeout(() => {
  // code to run at a later time
}, 0);

By employing this method, it allows the event loop an opportunity to handle other tasks before executing the code enclosed within this block.

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

Angular 10 Reactive Form - Controlling character limit in user input field

I'm currently developing an Angular 10 reactive form and I am looking for a way to restrict the maximum number of characters that a user can input into a specific field. Using the maxLength Validator doesn't prevent users from entering more chara ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...

Issue with sidebar expand/collapse functionality on desktop devices

The mobile version of the Expand/Collapse feature is functioning properly, but it seems to have issues on desktop. Originally written in ReactJS, I integrated it into NextJS and utilized Tailwind for its CSS styling. Despite my attempts to troubleshoot an ...

Is there a way to deactivate a tab when it's active and reactivate it upon clicking another tab in Angular?

<a class="nav-link" routerLink="/books" routerLinkActive="active (click)="bookTabIsClicked()" > Books </a> I am currently teaching myself Angular. I need help with disabling this tab when it is active ...

substitute one item with a different item

I am facing an issue with updating the address object within an organization object. I receive values from a form that I want to use to update the address object. However, when I try to change the address object in the organization using Object.assign, i ...

Error message: WebStorm shows that the argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type<any> | "root" | null} and InjectableProvider

Transitioning my app from Angular v5 to v6 has presented me with a TypeScript error when trying to define providedIn in my providers. The argument type {providedIn: "root"} cannot be assigned to the parameter type {providedIn: Type | "root" | null} & ...

Encountering challenges with the search and filtering features

I'm having some trouble with the search and filter features I'm creating. They work fine initially, but once I enter a search query in the input field, the results show up as expected. However, if I delete the query or enter a different one, the ...

Creating a Universally Unique Identifier in NextJs

I'm currently experimenting with the following code snippet: import { randomUUID } from 'crypto' var id = randomUUID() within my NextJs application, but unfortunately, I encountered the following error: index.js?46cb:369 Uncaught TypeErro ...

How to successfully utilize TypeScript ES6 modules and RequireJS for registering Angular elements

I am in the process of updating a current Angular application that uses AMD with TypeScript 1.5 ES6 module syntax. Our modules are currently stored in separate files, and the main "app" module is defined like this... define('app', ['angular ...

Angular router for displaying multiple view groups

What is the most effective strategy for handling two groups of views in Angular? Let me explain how I typically structure my layout in app.component.html: <app-header></app-header> <router-outlet></router-outlet> <app-footer> ...

Function modifies global variable

What could be causing the global variable to change when using the function write_ACK_ONLY()? I'm passing the array rxUartBuffer to write_ACK_ONLY() as data = new Array(20), but upon checking the Log Output, it seems that the function is also modifyin ...

Display issue with React TypeScript select field

I am working with a useState hook that contains an array of strings representing currency symbols such as "USD", "EUR", etc. const [symbols, setSymbols] = useState<string[]>() My goal is to display these currency symbols in a select field. Currently ...

The disappearance of the overlay background due to modal reload in NextJS dynamic routing

I am working on a simple NextJS app where clicking on a page opens a modal with updated URL but without triggering a new navigation. The content inside the modal is displayed, while the actual page location is reflected in the URL and refresh takes the use ...

Objects vanish 10 seconds after appearing [Angular2, *ngFor]

My Angular2 template is quite straightforward: <span *ngFor="let item of items"> {{ item.description }} </span> Here is the TypeScript logic for it: let list = new Map(); for(let j = 0; j < 100; j++) { list.set(j, { description: j.toS ...

How come JSON.parse is altering the data within nested arrays?

In my journey to master Angular 2, I decided to challenge myself by creating a Connect Four game using Angular CLI back when it was still utilizing SystemJS. Now, with the switch to the new Webpack-based CLI, I am encountering a peculiar issue... The fun ...

Developing OnIdle with rxjs

As I explore rxJS, I've come across this code snippet that monitors browser activity such as mouse movements, clicks, and keyboard usage. It's like the opposite of onIdle. import { fromEvent, throttle, debounce, interval, merge } from 'rxjs& ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Getting the Most Out of .find() in Angular 4

Despite reading various similar questions, I'm still struggling to make the .find() function work in my application. I have a service with the following API: export class VehicleService { private defUrl = 'API'; constructor(private ht ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

Error encountered while compiling NextJS: Unexpected use of single quotation mark in jsx-quotes

I can't seem to compile my NextJs 13 app without encountering errors. Take a look at my shortened eslintrc.js file below: module.exports = { env: { browser: true, es2021: true, }, extends: [ 'plugin:react/recommended', ...