Click here to Skip to main content
15,867,686 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
JavaScript
import React, { createContext, useContext, useEffect, useState } from 'react'
import { Text } from 'react-native';
import * as Google from "expo-google-app-auth";
import {
  GoogleAuthProvider,
  onAuthStateChanged,
  signInWithCredential,
  signOut,
} from "@firebase/auth";
import { auth } from "../firebase"

const AuthContext = createContext({});

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

export const AuthProvider = ({ children }) => {
  const [error, setError] = useState(null);
  const [user, setUser] = useState(null);
  const [loadingInitial, setloadingInitial] = useState(true);
  const [loading, setLoading] = useState(false);

  useEffect(
    () => 
      onAuthStateChanged(auth, (user)  => {
        if (user) {
          setUser(user);
        } else {
          setUser(null);
        }

        setloadingInitial(false);
        }),
      []
    );

  const logout = () => {
    setLoading(true);
    signOut(auth).catch((error) => setError(error)).finally(() => setLoading(false));
  };

  const signInWithGoogle = async () => {
    setLoading(true);
    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();
    })
      .catch((error) => setError(error))
      .finally(() => setLoading(false));
    
  };

  return (
    <AuthContext.Provider value=
    {{user, loading, error, signInWithGoogle, logout}}>
      {!loadingInitial && children}
    </AuthContext.Provider>
  );
};

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


What I have tried:

I think the problem is on user. When I delete user from value={{}}, it compiles.
Posted
Updated 26-Feb-22 3:46am
v3
Comments
Graeme_Grant 26-Feb-22 9:12am    
I'm not a React coder, but Google api documentation is very good. That is where I would start.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900