繁体   English   中英

首次使用 navigation.navigate 加载页面时未获取 currentUser.uid

[英]Not getting currentUser.uid when the page first loads using navigation.navigate

当页面首次加载时,我试图立即获取用户 UID 和用户 IDToken 并将其显示在控制台中,并使用这两者从后端检索用户数据。

我已经对用户进行了身份验证,并在运行于 expo 的 react-native 中登录了我的应用程序。

我将 UID 用作 URL 的一部分,并使用令牌对用户进行身份验证。

我也在控制台中记录这些数据。

当页面首次加载时,用户令牌正确显示在控制台上,但用户 UID 不是。 只有当我刷新页面时,用户 UID 才会显示在控制台中。

由于页面加载时未加载用户 UID,因此未正确触发用于获取发票的 function getUserInvoices(),并且我无法检索数据,因为我未通过后端进行身份验证。

我不确定为什么会这样,并且感到迷茫。 任何帮助,将不胜感激!

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"
    }
})

我也尝试查看 React Context,但根据我的理解(可能是错误的),它似乎主要用于在视觉上将数据从一个屏幕呈现到另一个屏幕,例如通过文本组件,但我试图在 useEffect 中访问此数据.

Firebase 身份验证自动将用户凭据保存到本地存储,并在应用程序重新启动时恢复它们。 但要做到这一点,它需要。 调用服务器(ao 检查帐户是否被怀疑),这意味着它是一个异步过程。 由于您的初始化代码在页面/应用程序加载时同步运行,因此它会在与服务器的检查完成之前检查currentUser - 此时它仍然是null

对于这种类型的场景,您需要使用auth state change listener ,它在服务器检查完成后第一次触发。 在 Firebase 之前,您可能想要显示一个 UI,表明您正在恢复用户配置文件。

所以像:

  1. 默认情况下将 state 变量isLoadingUser设置为true
  2. 呈现“正在恢复用户配置文件 UI”的isLoadingUser为真。
  3. 在屏幕加载时附加一个 auth state 更改侦听器。
  4. 当 auth state 更改回调触发时,将isLoadingUser设置为 false,并像现在一样呈现 UI。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM