Peter Malik
Peter Malik

Reputation: 463

Firebase getRedirectResult() doesn't solve

I am trying to implement the signInWithRedirect() function, but - weirdly enough , it doesn't work. In the below code , Check 2 and Check 3 never get logged - and no error is thrown :

const signInWithGoogle = async () => {
        try {
            console.log("Check 1")
            await signInWithRedirect(auth, googleAuthprovider);

            console.log("Check 2")
            const result = await getRedirectResult(auth);

            console.log("Check 3");
            if (result) {
                console.log(result.user);
            }

        } catch (e) {
            console.log(e.message.slice(10));
        }
    };

Also, if I use the exact same Google account to sign in with the signInWithPopup() method, everything works as expected:

const signInWithGoogle = async () => {
        const result = await signInWithPopup(auth, googleAuthprovider)

            const user = result.user;
            console.log(user)
    };

I'd really appreciate some help. Thanks!

Upvotes: 5

Views: 3487

Answers (1)

Harry Ronchetti
Harry Ronchetti

Reputation: 116

signInWithRedirect actually navigates away from the page and redirects back to your application so you'll need to handle responses in a separate function that fires when your application loads for the first time.

import {
  signInWithRedirect,
  getRedirectResult,
  GoogleAuthProvider,
} from "firebase/auth"
const googleAuthProvider = new GoogleAuthProvider()

// On Button Click
const signUpGoogle = async () => {
  try {
    await signInWithRedirect(auth, googleAuthProvider)
  } catch (error: any) {
    console.log(error)
  }
}
  
  
// When the page loads
const debugRedirectResult = async () => {
  try {
    const result = await getRedirectResult(auth)
    if (result) {
      const details = getAdditionalUserInfo(result)
      console.log(details) // details.isNewUser to determine if a new or returning user
    } else {
      // Everything is fine
    }
  } catch (error) {
    console.log(error) // Debug errors from redirect response
  }
}

For example, in React you'd do something like:

// Something like an Auth context provider or App.js
React.useEffect(() => {
  const debugRedirectResult = async () => {
    try {
      const result = await getRedirectResult(auth)
      if (result) {
        const details = getAdditionalUserInfo(result)
        console.log(details) // details.isNewUser to determine if a new or returning user
      } else {
        // Everything is fine
      }
    } catch (error) {
      console.log(error) // Debug errors from redirect response
    }
  }
  signInWithRedirect()
}, [])

Some things to be aware of:

Upvotes: 6

Related Questions