Home > Enterprise >  [Unhandled promise rejection: ReferenceError: Can't find variable: auth]
[Unhandled promise rejection: ReferenceError: Can't find variable: auth]

Time:08-13

I am pretty new to React Native; I have been trying to add google authentication via firebase and I keep running into this warning:

[Unhandled promise rejection: ReferenceError: Can't find variable: auth]
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:86:13 in tryCatch
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:66:31 in <anonymous>
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:86:13 in tryCatch
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:124:27 in invoke
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:148:16 in PromiseImpl$argument_0
at node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo
at node_modules\promise\setimmediate\core.js:200:22 in doResolve
at node_modules\promise\setimmediate\core.js:66:11 in Promise
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:147:15 in callInvokeWithMethodAndArg
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:152:154 in _invoke
at node_modules\@babel\runtime\helpers\regeneratorRuntime.js:238:57 in exports.async
at node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:123:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:177:14 in _callImmediatesPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:437:30 in callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:388:6 in __callImmediates
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:132:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:365:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:131:4 in flushedQueue

Here is my code:

import React, { createContext, useContext } from 'react';
import * as Google from "expo-google-app-auth";

import{
  GoogleAuthProvider,
  onAuthStateChanged,
  signInWithCredential,
  signOut,
} from "@firebase/auth";


const AuthContext = createContext({});

const config = {
  androidClientId: key,
  iosClientId: key,
  scopes: ['profile', 'email'],
  permissions: ['public_profile', 'email', 'gender', 'location'],
}

export const AuthProvider = ({children}) => {
  const signInWithGoogle = async () => {
      await Google.logInAsync(config).then(async (logInResult) => {
        if(logInResult.type === 'success'){
            const { idToken, accessToken }  = logInResult;
            const credential = GoogleAuthProvider.credential(idToken, accessToken);

            await signInWithCredential(auth, credential);
        }

        return Promise.reject();
      });
  };

    return (
      <AuthContext.Provider value ={{
          user: null,
          signInWithGoogle
      }}
      >
        {children}
      </AuthContext.Provider>
    );
};

export default function useAuth() {
    return useContext(AuthContext);
}

I pass the variable auth here:

await signInWithCredential(auth, credential);

However, no users show up on the authentication page of firebase, and I keep receiving this warning.

Thanks for your help!

CodePudding user response:

As the error says, you're trying to pass an auth variable to signInWithCredential, but you don't declare or initialize it anywhere. As shown in the documentation on getting started with Firebase Authentication on the web, you can get this with:

import { getAuth } from "firebase/auth";

// TODO: Replace the following with your app's Firebase project configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
  // ...
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);


// Initialize Firebase Authentication and get a reference to the service
const auth = getAuth(app);

CodePudding user response:

Please refer to the official documentation provided by firebase for google auth

The google-signin library provides a wrapper around the official Google login library, allowing you to create a credential and sign-in to Firebase.

Most configuration is already setup when using Google Sign-In with Firebase, however you need to ensure your machines SHA1 key has been configured for use with Android. You can see how to generate the key on the Getting Started documentation.

Ensure the "Google" sign-in provider is enabled on the Firebase Console.

Follow these instructions to install and setup google-signin

Before triggering a sign-in request, you must initialize the Google SDK using your any required scopes and the webClientId, which can be found in the android/app/google-services.json file as the client/oauth_client/client_id property (the id ends with .apps.googleusercontent.com). Make sure to pick the client_id with client_type: 3

    import { GoogleSignin } from '@react-native-google-signin/google-signin';
    
    GoogleSignin.configure({
      webClientId: '',
    });

Once initialized, setup your application to trigger a sign-in request with Google using the signIn method.

    import React from 'react';
    import { Button } from 'react-native';
    
    function GoogleSignIn() {
      return (
        <Button
          title="Google Sign-In"
          onPress={() => onGoogleButtonPress().then(() => console.log('Signed in with Google!'))}
        />
      );
    }

The onGoogleButtonPress can then be implemented as follows:

    import auth from '@react-native-firebase/auth';
    import { GoogleSignin } from '@react-native-google-signin/google-signin';
    
    async function onGoogleButtonPress() {
      // Get the users ID token
      const { idToken } = await GoogleSignin.signIn();
    
      // Create a Google credential with the token
      const googleCredential = auth.GoogleAuthProvider.credential(idToken);
    
      // Sign-in the user with the credential
      return auth().signInWithCredential(googleCredential);
    }

Upon successful sign-in, any onAuthStateChanged listeners will trigger with the new authentication state of the user.

  • Related