How do I make a JavaScript button call the new Firebase (v9.0.0+) signInWithPopup

Viewed 306

I'm unfamiliar with Javascript and I'm wondering how can a button call a function, more specifically Firebase's new signInWithPopup syntax introduced in version 9.0.0+. I want to popup the authentication for signing in with Google when the user clicks the button. Unless I am misreading https://firebase.google.com/docs/auth/web/google-signin#web-version-9_4 and the code they provided is incomplete? (I have all the prerequisite code: imports, consts, etc).

signInWithPopup(auth, provider)
  .then((result) => {
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;
    const user = result.user;
  }).catch((error) => {
    const errorCode = error.code;
    const errorMessage = error.message;
    const email = error.email;
    const credential = GoogleAuthProvider.credentialFromError(error);
  });

I've tried

<button onClick='signInWithPopup()'>Sign In With Google</button>

and

<button onClick={signInWithPopup()}>Sign In With Google</button>

All my attempts just resulted in a button that just clicks and doesn't do anything.

Edit: Ah, I had to add the parameters auth and provider.

1 Answers

Try wrapping Firebase's signInWithPopUp in your own function as shown below:

import { getAuth, signInWithPopup, GoogleAuthProvider } from "firebase/auth";

const auth = getAuth(app) // import auth instance 

const googleSignIn = async () => {
  try {
    const provider = new GoogleAuthProvider();
    const result = await signInWithPopup(auth, provider)
    const credential = GoogleAuthProvider.credentialFromResult(result);
    const token = credential.accessToken;
    console.log(credential)
  } catch (e) {
    console.log(e.code, e.message)
  }
}
<button onClick={googleSignIn}>Sign In With Google</button>
// use that function ^
Related