Why isn't the google accounts login page showing up even though I have implemented the expo auth session library with react native? - react-native

I have been following the tinder 2.0 react native tutorial https://youtu.be/qJaFIGjyRms At 1:04:00 he sets the sign in method to: "await Google.logInAsync()" but I have noticed the google app auth library used in the video is now deprecated, I am redirected to use expo auth session instead, with this new library I cannot tell whether the google sign in is working or not as I am simply redirected back to the homepage after clicking the login button.
Here is my code with response printed in the console:
Screenshot:
code:
import React, { createContext, useContext } from 'react'
import * as WebBrowser from "expo-web-browser";
import { Button } from "react-native";
import * as Google from "expo-auth-session/providers/google";
import { useEffect, useState } from "react";
import { useNavigation } from "#react-navigation/native";
import { GoogleAuthProvider, signInWithCredential } from 'firebase/auth';
const AuthContext = createContext({});
const user = null
WebBrowser.maybeCompleteAuthSession();
const GoogleLogin = () => {
const navigation = useNavigation();
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId:
"236293699216-bst43767un873mcddmmrpgf4v2h088jd.apps.googleusercontent.com",
iosClientId:
"236293699216-6jdpm0rd6kn5d0qlbh1vgva5afgbqgib.apps.googleusercontent.com",
webClientId:
"236293699216-9a0nknjdq7ie79h40iubg0tddokgogfv.apps.googleusercontent.com",
scopes: ["profile", "email"],
permissions: ["public_profile","email", "gender", "location"],
});
const asyncAuthRequest = async () => {
if (response?.type === "success") {
const { authentication } = response;
// await AsyncStorage.setItem("accessTocken", "hihi");
//navigation.navigate"Home");
const { idToken, accessToken} = response;
const credential = GoogleAuthProvider.credential(idToken, accessToken);
await signInWithCredential(auth, credential)
}
return Promise.reject();
};
useEffect(() => {
asyncAuthRequest();
}, [response]);
console.log('response', response)
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync();
}}
/>
);
};
export default GoogleLogin;

Related

possible unhandled promise rejection request while google aunthentication

I am getting the following error while trying to integrate the google login into a react native app and got the following error. It was working fine before. Could someone help. Unable to figure the error
import type {Node} from 'react';
import { GoogleSignin } from '#react-native-google-signin/google-signin';
import auth from '#react-native-firebase/auth';
import {
SafeAreaView,
ScrollView,
StatusBar,
StyleSheet,
Text,
useColorScheme,
View,
Button
} from 'react-native';
const App: () => Node = () => {
GoogleSignin.configure({
webClientId: 'xxx',
});
const signInWithGoogleAsync = async() => {
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
const user_sign_in = auth().signInWithCredential(googleCredential);
user_sign_in.then((user) =>{
console.log(user);
})
.catch((error)=>{
console.log(error);
})
}
return (
<View style={{flex:1, justifyContent:'center', alignItems:'center'}}>
<Button
title='Sign in with Google'
onPress={signInWithGoogleAsync}
/>
</View>
);
};
export default App;

Problem with Expo Google signin on Device

I followed every single step on the tutorial page of Expo.dev to create a login page using Google Oauth.
I get the browser to open and I select a google account but the response I get back is *
Object {
"type": "dismiss",
}
Here is my code, literally copied and pasted from the tutorial page of the official expo dev site
import * as React from 'react';
import * as WebBrowser from 'expo-web-browser';
import * as Google from 'expo-auth-session/providers/google';
import { Button } from 'react-native';
WebBrowser.maybeCompleteAuthSession();
export default function App() {
const [request, response, promptAsync] = Google.useAuthRequest({
expoClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
iosClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
androidClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
webClientId: 'GOOGLE_GUID.apps.googleusercontent.com',
});
React.useEffect(() => {
if (response?.type === 'success') {
const { authentication } = response;
}
}, [response]);
return (
<Button
disabled={!request}
title="Login"
onPress={() => {
promptAsync();
}}
/>
);
}

How to change routes when auth status changes in React Native

What I need to do is to render the react native routes based on the users auth status. Right now I am doing this the wrong way, by having an interval running to check for auth status change:
import React, { useState, useEffect } from 'react';
import { AppLoading } from 'expo';
import { checkAuth } from './auth';
import { LoggedInRoutes, LoggedOutRoutes } from './router';
export default () => {
const [isReady, setReady] = useState(false);
const [loggedIn, setLoggedIn] = useState(false);
useEffect(() => {
setInterval(() => {
checkAuth()
.then((res) => { setLoggedIn(res); setReady(true); console.log('checked..') })
.catch((err) => alert(err));
}, 1500);
}, [loggedIn]);
if (!isReady) {
return (
<AppLoading
onFinish={() => setReady(true)}
/>
);
}
return (
loggedIn ? <LoggedInRoutes /> : <LoggedOutRoutes />
);
}
But obviously that is quite bad. I am using async storage to save the user when he authenticates and remove him from storage when he clicks the logout button.
Is there a way to check for changes in async storage and re-render the routes? or run a function that changes loggedIn state when user click login/logout button?
I would recommend to use switchNavigator in react navigation
reactnavigation.org/docs/4.x/auth-flow – mr-nobody 40 secs ago Edit Delete
this approach will works like a charm.
import React, {useState, useEffect} from 'react';
import OnBoardingRoutes from './onBoarding.routes';
import AppRoutes from './app.routes';
import checkFirstUsage from "./checkFirstUsage/path";
const Routes: React.FC = () => {
const [loading, setLoading] = useState(true)
const [firstUsage,setFirstUsage] =useState(null);
useEffect(() => {
async function check() {
const fU = await checkFirstUsage()
setFirstUsage(fU)
setLoading(false)
}
check()
},[])
if (loading) return null // or any better component
return firstUsage ? <OnBoardingRoutes /> : <AppRoutes />;
};
export default Routes;

undefined is not an object evaluating '_ usecontext.user'

I am getting this error in a big react native app. Actually I am running this on expo. Can anyone see through and suggest a solution.Please Help
"undefined is not an object evaluating '_ usecontext.user'"
import React, { useState } from "react";
import { StyleSheet, Image } from "react-native";
import * as Yup from "yup";
import Screen from "../components/Screen";
import {
ErrorMessage,
Form,
FormField,
SubmitButton,
} from "../components/forms";
import authApi from "../api/auth";
import useAuth from "../auth/useAuth";
const validationSchema = Yup.object().shape({
email: Yup.string().required().email().label("Email"),
password: Yup.string().required().min(4).label("Password"),
});
function LoginScreen(props) {
const auth = useAuth();
const [loginFailed, setLoginFailed] = useState(false);
const handleSubmit = async ({ email, password }) => {
const result = await authApi.login(email, password);
if (!result.ok) return setLoginFailed(true);
setLoginFailed(false);
auth.logIn(result.data);
};
//not full code here
}
#auth.js (AuthApi) #
mport client from "./client";
const login = (email, password) => client.post("/auth", { email, password });
export default {
login,
};
#useAuth#
import { useContext } from "react";
import jwtDecode from "jwt-decode";
import AuthContext from "./context";
import authStorage from "./storage";
export default useAuth = () => {
const { user, setUser } = useContext(AuthContext);
const logIn = (authToken) => {
const user = jwtDecode(authToken);
setUser(user);
authStorage.storeToken(authToken);
};
const logOut = () => {
setUser(null);
authStorage.removeToken();
};
return { user, logIn, logOut };
};
#AuthContext#
import React from "react";
const AuthContext = React.createContext();
export default AuthContext;
Tell me if you need more code. Please Help

React Native Navigate To Another Screen Automatically

I am trying to navigate back to the LogIn screen as soon as logout.js is hit.
At one point this seemed to work and then stopped and I can't work out why.
Here is my code:
import React, { Component } from 'react';
import { Text, View, Button } from 'react-native';
import * as SecureStore from 'expo-secure-store';
import { globalStyles } from '../styles/global';
export default class App extends Component {
componentDidMount() {
(async () => {
const token = await SecureStore.getItemAsync('token');
// Your fetch code
this.setState({loaded:false, error: null});
let url = 'https://www.example.com/api/auth/logout';
let h = new Headers();
h.append('Authorization', `Bearer ${token}`);
h.append('Content-Type', 'application/json');
h.append('X-Requested-With', 'XMLHttpRequest');
let req = new Request(url, {
headers: h,
method: 'GET'
});
fetch(req)
.then(response=>response.json())
//.then(this.showData)
.catch(this.badStuff)
})();
this.deleteToken()
}
badStuff = (err) => {
this.setState({loaded: true, error: err.message});
}
deleteToken() {
(async () => {
const token = await SecureStore.deleteItemAsync('token')
});
this.goToLogInScreen()
}
goToLogInScreen() {
this.props.navigation.navigate('LogIn')
}
render() {
return (
<View style={globalStyles.container}>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('LogIn')}
/>
</View>
);
}
}
I need the code to:
Send the command to the API to log out
Delete the token from SecureStore
Navigate to the LogIn screen (containing the log in form).