【发布时间】:2021-02-15 23:40:46
【问题描述】:
我目前正在使用 Typescript 创建一个 React Native 移动应用程序。
应用通过 Google OAuth Provider 使用 Firebase 身份验证。
为了使用用户名和其他一些详细信息(从 Firestore 中检索),我正在使用 React Provider,如下例所示:
import React, {useState, useEffect} from 'react';
import auth from '@react-native-firebase/auth';
import { GoogleSignin } from '@react-native-community/google-signin';
import firestore from '@react-native-firebase/firestore';
GoogleSignin.configure({
webClientId: 'x.googleusercontent.com',
});
const getUserById = async (id: string) => {
const admin = await firestore().collection("users").doc(id).collection("priv").doc("admin").get();
const prot = await firestore().collection("users").doc(id).collection("priv").doc("protected").get();
const jsonData = {
admin: admin.data(),
protected: prot.data(),
};
return jsonData;
}
const AuthContext = React.createContext({});
function AuthProvider(props: any) {
const [user, setUser] = useState(auth().currentUser);
const [details, setDetails] = useState({});
const [initializing, setInitializing] = useState(true);
const onAuthStateChanged = async (authUser: any) => {
setUser(authUser);
if (authUser !== null)
refreshDetails();
}
const refreshDetails = async () => {
const details = (await getUserById(user.uid));
setDetails(details);
}
useEffect(() => {
const subscriber = auth().onAuthStateChanged(onAuthStateChanged);
return subscriber; // unsubscribe on unmount
}, []);
const loginWithGoogle = 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
return auth().signInWithCredential(googleCredential);
}
const logout = () => {
auth()
.signOut()
}
return (
<AuthContext.Provider value={{user, loginWithGoogle, logout, refreshDetails, details, initializing}} {...props}></AuthContext.Provider>
)
}
const useAuth = () => {
const state = React.useContext(AuthContext);
return {
...state,
};
}
export {AuthProvider, useAuth};
正如您在示例中所见,我正在使用 React 中的 useEffect 方法来订阅身份验证更改。
很遗憾,如果我关闭应用程序并重新打开它,则不会触发此身份验证更改,因此未设置 user 状态,我会收到一堆错误。
在这种情况下,最佳做法是什么?我想我只需要在应用再次启动时触发onAuthStateChangeEvent。
感谢大家的帮助 IJustDev
【问题讨论】:
标签: javascript firebase react-native firebase-authentication