Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

onAuthStateChange or persist no longer works on react native expo apps!!!! #7152

Closed
thesoicalapp91 opened this issue Mar 24, 2023 · 10 comments
Closed

Comments

@thesoicalapp91
Copy link

Please fix this issue asap! Google, github, chatGPT nobody can get the user to stay logged in after refreshing the app in version 9!!!!!!! Please fix this and give the code example documentation!!! "Persist" dose not work on react native apps built with npx create-expo-app.

@google-oss-bot
Copy link
Contributor

I couldn't figure out how to label this issue, so I've labeled it for a human to triage. Hang tight.

@isaacrowntree
Copy link

Also happens on normal react.

@thesoicalapp91
Copy link
Author

Also happens on normal react.
Replying to (isaacrowntree) and anyone who wants to recreate the issue. Please check this tutorial as I believe it works with react and testing on web but dose not work on ios, android or device.

https://www.youtube.com/watch?v=Vv_Oi7zPPTw&list=PLegDINiuhUbC_tZkBwSWXSFOiPgUieSq2&index=7&t=1115s&ab_channel=webdecoded

@NhienLam
Copy link
Contributor

Hi thesoicalapp91, thanks for reporting.
Can you tell us more about your environment? Are you using v9 compat or v9 modular?

This may be similar to #6732 and #6050. Can you try upgrading to v9 modular and see if the issue still happens?

@thesoicalapp91
Copy link
Author

Hi NhienLam, both unfortunately. I used compat for my old project that was running on my mac Catalina. I then bit the bullet with a complete system update to Ventura for the specific reason of creating a new npx-create-expo-app with all the latest SDK's, setup etc and specifically to fix the firebase issue however, the new v9 code does not work on my completely new Ventura system set up either (in a new npx-create-expo-app not my old app). And yes, it seams to be the same issue as #6732 and #6050. I'm going to give #6050 a try.

@thesoicalapp91
Copy link
Author

Checked out the other issues but not really a proper fix... Added a storage token await layer, now getting the token, but sign out and token removal stops working. A user can log out and anyone can log back using incorrect credentials as the token stays around. Tried adding basic state hooks but I cant spend any more time on this today. Will try again during the week. Bit annoying really...

@NhienLam
Copy link
Contributor

Thanks for the update @thesoicalapp91.
Which react version are you using? Are you using the latest version? Auth compat uses AsyncStorage from the React Native core package, which is deprecated and getting removed. On v9 modular, this is being fixed to use the supported react-native-async-storage package in #7128.

Can you share some code snippets after upgrading to v9 modular, for how you are using async storage?

@thesoicalapp91
Copy link
Author

thesoicalapp91 commented Mar 31, 2023

Thanks with help from #7164 I've managed to fix this and put a link to my answer:

https://stackoverflow.com/questions/75669669/how-to-persist-firebase-user-auth-on-react-native/75898568#75898568

The steps to fix this are:

Versions

"expo": "~48.0.6",

"react": "18.2.0",

npm i firebase
("firebase": "^9.19.0")

npm i @react-native-async-storage/async-storage
("@react-native-async-storage/async-storage": "1.17.11")

npm i @react-native-firebase/auth
("@react-native-firebase/auth": "^17.4.0")

Create a firebaseConfig.js file

import AsyncStorage from "@react-native-async-storage/async-storage";
import { initializeApp } from "firebase/app";
import {
getReactNativePersistence,
initializeAuth,
} from "firebase/auth/react-native";

export const firebaseApp = initializeApp({
// enter your firebase project details
apiKey: "..........",
authDomain: "..........",
projectId: "..........",
storageBucket: "..........",
messagingSenderId: "..........",
appId: "..........",
measurementId: ".........."
});

export const auth = initializeAuth(firebaseApp, {
persistence: getReactNativePersistence(AsyncStorage),
});

Create App.js

import {StyleSheet} from 'react-native';
import AppMain from './AppMain';

const App = () => {
return (
AppMain />
);
};

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff'
}
});

export default App;

Create AppMain.js

import { useEffect, useState } from 'react';
import { StyleSheet, Text, View, Button, Dimensions, TextInput, ActivityIndicator, Pressable } from 'react-native';
import { auth } from './firebaseConfig';

import { signInWithEmailAndPassword, onAuthStateChanged, signOut } from "firebase/auth";

const { width, height } = Dimensions.get('window');
console.log(width, height);

export default function App() {
const [user, setUser] = useState(null);
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');

useEffect(() => {
onAuthStateChanged(auth, (user) => {
console.log("USER IS STILL LOGGED IN: " , user);
if (user) {
setUser(user);
}
});
}, [user]);

const handleLogin = () => {
signInWithEmailAndPassword(auth, email, password)
.then((userCredential) => {
console.log('User logged in successfully:', userCredential);
setUser(userCredential);
})
.catch((error) => {
console.log('Error', error);
});
};

const handleLogout = () => {
signOut(auth)
.then(() => {
console.log('User logged out successfully:');
setUser(null);
})
.catch((error) => {
console.log('Error', error);
});
};

if (!user) {
return (

<TextInput
placeholder="Email"
value={email}
onChangeText={(text) => setEmail(text)}
/>
<TextInput
placeholder="Password"
secureTextEntry={true}
value={password}
onChangeText={(text) => setPassword(text)}
/>

{'\nYou Are Logged Out.'}

);
};

if (user) {
return (

<Text style={[styles.text,{fontWeight: 'bold'}]}>{"USER STILL LOGGED IN: \n\n"}
{'email: ' + user?.email}
{'uid: ' + user?.uid}
{"\nAccess Token:\n\n" + user?.accessToken}



);
};
};

const styles = StyleSheet.create({
container: {
flex: 1,
width: width,
height: height,
backgroundColor: '#fff',
justifyContent: 'center',
alignItems:'center'
},
text: {
color:'#000',
textAlign: 'center',
paddingHorizontal:20
}
});

The following steps should keep the user logging in after refreshing the app. It also handles the sign in and sign out functions. This issue was bugging me for a while :).

@thesoicalapp91
Copy link
Author

thesoicalapp91 commented Mar 31, 2023

Hi NhienLam - Below is my packadge.json and import statements if that helps? I'll try and add some snippets this week however I'm deleting all the code as its just trial and error at this point.

{ "name": "firebasev9", "version": "1.0.0", "main": "node_modules/expo/AppEntry.js", "scripts": { "start": "expo start", "android": "expo start --android", "ios": "expo start --ios", "web": "expo start --web" }, "dependencies": { "@expo/webpack-config": "^18.0.1", "@react-native-async-storage/async-storage": "^1.17.11", "expo": "~48.0.9", "expo-status-bar": "~1.4.4", "firebase": "^9.18.0", "install": "^0.13.0", "npm": "^9.6.2", "react": "18.2.0", "react-dom": "18.2.0", "react-native": "0.71.4", "react-native-web": "~0.18.10" }, "devDependencies": { "@babel/core": "^7.20.0" }, "private": true }

import { onAuthStateChanged, signOut } from "firebase/auth"; import AsyncStorage from "@react-native-async-storage/async-storage";

Im not using compat as I created a new app to transfer the old project into the new app. I'm trying to redo the onAuthStateCahnge with v9 that's not working on react native with expo.

Thanks for the update @thesoicalapp91. Which react version are you using? Are you using the latest version? Auth compat uses AsyncStorage from the React Native core package, which is deprecated and getting removed. On v9 modular, this is being fixed to use the supported react-native-async-storage package in #7128.

Can you share some code snippets after upgrading to v9 modular, for how you are using async storage?

Hi NhienLam - I've added an answer above with my stack overflow answer link. It's fixed for me so this can be closed from my point of view. Thanks for the help.

@thesoicalapp91 thesoicalapp91 changed the title onAuthStateChange or persist whatever no longer works on react native expo apps!!!! onAuthStateChange or persist no longer works on react native expo apps!!!! Mar 31, 2023
@thesoicalapp91
Copy link
Author

thesoicalapp91 commented Mar 31, 2023

Also happens on normal react.

Hi [isaacrowntree], Try the steps above and in : https://stackoverflow.com/questions/75669669/how-to-persist-firebase-user-auth-on-react-native/75898568#75898568

@firebase firebase locked and limited conversation to collaborators May 6, 2023
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants