[英]Not getting currentUser.uid when the page first loads using navigation.navigate
When the page first loads, I am trying to immediately get the user UID and user IDToken and display it in the console, as well as use both of these to retrieve user data from the backend.当页面首次加载时,我试图立即获取用户 UID 和用户 IDToken 并将其显示在控制台中,并使用这两者从后端检索用户数据。
I have already authenticated the user and logged into my application in react-native running on expo.我已经对用户进行了身份验证,并在运行于 expo 的 react-native 中登录了我的应用程序。
I am using the UID as part of the URL, and the token to authenticate the user.我将 UID 用作 URL 的一部分,并使用令牌对用户进行身份验证。
I am also logging this data in the console.我也在控制台中记录这些数据。
When the page first loads, the user Token is being displayed on the console correctly, but the user UID is not.当页面首次加载时,用户令牌正确显示在控制台上,但用户 UID 不是。 Only when I refresh the page is the user UID then displayed in the console.只有当我刷新页面时,用户 UID 才会显示在控制台中。
Because the User UID is not loading on page load, the function to get invoices, getUserInvoices() properly is not being triggered, and I am not able to retrieve data because I am not authenticated with the backend.由于页面加载时未加载用户 UID,因此未正确触发用于获取发票的 function getUserInvoices(),并且我无法检索数据,因为我未通过后端进行身份验证。
I'm not sure why this is happening, and am feeling lost.我不确定为什么会这样,并且感到迷茫。 Any help would be appreciated!任何帮助,将不胜感激!
import { StyleSheet, Text, View } from 'react-native'
import React, { useEffect, useState} from 'react'
import {auth} from '../firebase';
const InvoicesScreen = () => {
const [myIdToken, setMyIdToken] = useState('');
const [myUserUID, setMyUserUID] = useState('');
const [userCurrency, setUserCurrency] = useState([]);
React.useEffect(() => {
async function getUserUID() {
if (auth.currentUser) {
setMyUserUID(auth.currentUser?.uid);
console.log('\nUser UID = ',myUserUID, `\n`);
}
} //end of function to get user UID
async function getUserInvoices() {
await fetch(`https://testing123/${myUserUID}/details/all`, {
headers: {
'Authorization': `Bearer ${myIdToken}`
}
})
.then((response) => {return response.json()})
.then((text) => {
console.log('\n');
console.log('Invoice Info: ', text);
console.log('\n');
for (let i=0;i<text.length;i++) {
setUserCurrency([...userCurrency, text[i].amount.currency])
}
console.log(userCurrency)
console.log('\n*********************************************************************************************************************************')
// console.log(text.length)
// console.log(text[0].amount.currency)
// console.log(text[0].country)
})
} //end of getUserInvoices() function
async function getUserIdToken() {
await auth.currentUser?.getIdToken().then((token) => {
if (auth.currentUser) {
setMyIdToken(token);
console.log('\n*********************************************************************************************************************************')
console.log('\n\nUser Token: ', token, '\n');
// getUserUID();
// getUserInvoices();
//tried running it inside this function too, but it also didn't work
}
})
} //end of function setting user JSON token in the myIdToken variable
//tried doing this too, but it still didn't work as well
// getUserUID().then(() => {
// getUserIdToken().then(() => {
// getUserInvoices();
// })
// })
getUserUID();
getUserIdToken();
getUserInvoices();
}, []);
return (
<View style={styles.container}>
<Text>InvoicesScreen</Text>
</View>
)
}
export default InvoicesScreen
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: "center",
alignItems: "center"
}
})
I also tried looking into React Context, but from my understanding (might be wrong) it seems like it's mainly used for rendering data from one screen to another visually, for example through a Text component, but I am trying to access this data inside useEffect.我也尝试查看 React Context,但根据我的理解(可能是错误的),它似乎主要用于在视觉上将数据从一个屏幕呈现到另一个屏幕,例如通过文本组件,但我试图在 useEffect 中访问此数据.
Firebase Authentication automatically persists the user credentials to local storage, and restores them when the app restarts. Firebase 身份验证自动将用户凭据保存到本地存储,并在应用程序重新启动时恢复它们。 But to do that, it needs to.但要做到这一点,它需要。 make a call to the server (ao to check if the account was suspected), which means it's an asynchronous process.调用服务器(ao 检查帐户是否被怀疑),这意味着它是一个异步过程。 Since your initialization code runs synchronously when the page/app loads, it checks currentUser
before the check with the server has completed - at which point it will still be null
.由于您的初始化代码在页面/应用程序加载时同步运行,因此它会在与服务器的检查完成之前检查currentUser
- 此时它仍然是null
。
For this type of scenario you'll want to use an auth state change listener , which fires for the first time after the check with the server has completed.对于这种类型的场景,您需要使用auth state change listener ,它在服务器检查完成后第一次触发。 Until that Firebase, you might want to show a UI that says you're restoring the user profile.在 Firebase 之前,您可能想要显示一个 UI,表明您正在恢复用户配置文件。
So something like:所以像:
isLoadingUser
to true
by default.默认情况下将 state 变量isLoadingUser
设置为true
。isLoadingUser
is true.呈现“正在恢复用户配置文件 UI”的isLoadingUser
为真。isLoadingUser
to false, and render the UI as you do now.当 auth state 更改回调触发时,将isLoadingUser
设置为 false,并像现在一样呈现 UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.