How do I implement expo-auth-session with Firebase?

Viewed 51

I want my code to allow the user to login and authenticate with Google, and once they have, for them to be added to my authentication database in Firebase.

I've attempted to do this with the following code:

import React, { createContext, useContext } from 'react'
import * as Google from 'expo-auth-session/providers/google';
import * as WebBrowser from 'expo-web-browser';
import {
    GoogleAuthProvider,
    onAuthStateChanged,
    signInWithCredential,
    signOut,
} from "@firebase/auth";

const AuthContext = createContext({});

WebBrowser.maybeCompleteAuthSession();

const config = {
    androidClientId: "x",
    iosClientId: "x",
    expoClientId: "x",
    scopes: ["profile", "email"],
    permissions: ["public_profile", "email", "gender", "location"]
}

export const AuthProvider = ({children}) => {


    const signInWithGoogle = async () => {
        await Google.useAuthRequest(config).then(async (logInResult) =>{
            if(logInResult.type === 'success'){
                //login
                const {idToken, accessToken} = logInResult;
                const credential = GoogleAuthProvider.credential(idToken, accessToken);

                await signInWithCredential(credential);
            }

            return Promise.reject();
        });
    }

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

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

However, when I try to run my code, this is the error I get:

[Unhandled promise rejection: Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one 

How can I fix this error?

1 Answers

I think the error is that you're creating a whole component to expose the useContext, you can just do something like this:

export const useAuth= () =>
  useContext(AuthContext)

Related