-1

Why doesn't it show me the user uid on the screen? I have a simple firebase authentication with email in a React Native app. Everything works perfectly, the Login and SignUp. User seamlessly logs into Firebase. But when I want it to show me the user's UID and I add this code snippet, it shows me the error and the App breaks:

<Text> Welcome Social Network {user.uid} </Text>

I have seen other examples of colleagues in which it does work, using the same code, but I do not understand mine because it does not work for me

I have searched the internet for solutions without success. I have seen similar problems, other questions similar to mine on this site, but not the same, since as I say, this code works for other people, but not for me. if I delete the fragment "{user.uid}" everything works perfectly

Error displayed by the console:

TypeError: Cannot read properties of null (reading 'uid')

***This error is located at:
    in HomeScreen (at SceneView.tsx:126)
    in StaticContainer
    in EnsureSingleNavigator (at SceneView.tsx:118)
    in SceneView (at useDescriptors.tsx:210)
    in RCTView (at View.js:32)
    in View (at CardContainer.tsx:280)
    in RCTView (at View.js:32)
    in View (at CardContainer.tsx:278)
    in RCTView (at View.js:32)
    in View (at CardSheet.tsx:33)
    in CardSheet (at Card.tsx:557)
    in RCTView (at View.js:32)
    in View (at createAnimatedComponent.js:242)
    in AnimatedComponent (at createAnimatedComponent.js:295)
    in AnimatedComponentWrapper (at Card.tsx:536)
    in PanGestureHandler (at GestureHandlerNative.tsx:14)
    in PanGestureHandler (at Card.tsx:530)
    in RCTView (at View.js:32)
    in View (at createAnimatedComponent.js:242)
    in AnimatedComponent (at createAnimatedComponent.js:295)
    in AnimatedComponentWrapper (at Card.tsx:526)
    in RCTView (at View.js:32)
    in View (at Card.tsx:520)
    in Card (at CardContainer.tsx:218)
    in CardContainer (at CardStack.tsx:649)
    in RNSScreen (at createAnimatedComponent.js:242)
    in AnimatedComponent (at createAnimatedComponent.js:295)
    in AnimatedComponentWrapper (at src/index.native.tsx:171)
    in Screen (at Screens.tsx:37)
    in MaybeScreen (at CardStack.tsx:642)
    in RNSScreenContainer (at src/index.native.tsx:238)
    in ScreenContainer (at Screens.tsx:20)
    in MaybeScreenContainer (at CardStack.tsx:561)
    in RCTView (at View.js:32)
    in View (at Background.tsx:13)
    in Background (at CardStack.tsx:559)
    in CardStack (at StackView.tsx:437)
    in RNCSafeAreaProvider (at SafeAreaContext.tsx:76)
    in SafeAreaProvider (at SafeAreaProviderCompat.tsx:46)
    in SafeAreaProviderCompat (at StackView.tsx:430)
    in RCTView (at View.js:32)
    in View (at StackView.tsx:429)
    in StackView (at createStackNavigator.tsx:118)
    in Unknown (at createStackNavigator.tsx:117)
    in StackNavigator (at AppStack.js:9)
    in AppStack (at Routes.js:28)
    in EnsureSingleNavigator (at BaseNavigationContainer.tsx:430)
    in BaseNavigationContainer (at NavigationContainer.tsx:132)
    in ThemeProvider (at NavigationContainer.tsx:131)
    in NavigationContainerInner (at Routes.js:27)
    in Routes (at navigation/index.js:9)
    in AuthProvider (at navigation/index.js:8)
    in Providers (at App.js:5)
    in App (at renderApplication.js:50)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:92)
    in RCTView (at View.js:32)
    in View (at AppContainer.js:119)
    in AppContainer (at renderApplication.js:43)
    in pinkilinkyApp(RootComponent) (at renderApplication.js:60)***

Here is my code:

HomeScreen.js

import React, { useContext } from "react"
import { View, Text, StyleSheet } from "react-native"
import auth from '@react-native-firebase/auth'

import FormButton from "../components/FormButton"
import { AuthContext } from "../navigation/AuthProvider"
import globalStyles from "../styles/global"

const HomeScreen = () => {

  const { user, logout } = useContext(AuthContext)
  return (
    <View style={globalStyles.containerHome}>
      <Text style={globalStyles.textHome}>Welcome  {user.uid} </Text>
      <FormButton buttonTitle="Logout" onPress={() => logout()} />
    </View>
  )
}

export default HomeScreen

Routes.js

import React, { useContext, useEffect, useState } from 'react'
import { NavigationContainer } from '@react-navigation/native'
import auth from '@react-native-firebase/auth'
    
import { AuthContext } from './AuthProvider'
import AuthStack from './AuthStack'
import AppStack from './AppStack'

const Routes = () => {

  const [initializing, setInitializing] = useState(true)
  const [user, setUser] = useState()

  const onAuthStateChanged = (user) => {
    setUser(user)
    if (initializing) setInitializing(false)
  }

  useEffect(() => {
    const subscriber = auth().onAuthStateChanged(onAuthStateChanged)
    return subscriber // unsubscribe on unmount
  }, [])

  if (initializing) return null// podemos usar un cargador mientras carga firebase

  return ( 
    <NavigationContainer>
      { user ? <AppStack/> : <AuthStack/> }
    </NavigationContainer>
    )
}
  
export default Routes

AuthProvider.js

import React, { createContext, useState } from "react";
import auth from "@react-native-firebase/auth";

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  return (
    <AuthContext.Provider
      value={{
        user,
        setUser,
        login: async (email, password) => {
          try {
            await auth().signInWithEmailAndPassword(email, password);
          } catch (e) {
            console.log(e);
          }
        },
        register: async (email, password) => {
          try {
            await auth().createUserWithEmailAndPassword(email, password);
          } catch (e) {
            console.log(e);
          }
        },
        logout: async () => {
          try {
            await auth().signOut();
          } catch (e) {
            console.log(e);
          }
        }
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export default AuthProvider;

I hope it's enough for you to see where my mistake is.

Ako
  • 1,424
  • 12
  • 18
  • Ad the time of first rendering `user` object still `null` – Dmitrii Zolotuhin Oct 23 '21 at 14:01
  • I have changed that to an empty string `(const [user, setUser] = useState (''))`, this does not give error, but does not show the UID of the user – juan José Oct 23 '21 at 14:07
  • Of course it was a big mistake and I apologize @Japsz I have taken advantage of the circumstances. I think you should answer the question, I'll delete mine. – Estudiante Nov 01 '21 at 08:21
  • 2
    No worries @Estudiante ! i was just pointing out the question was already answered on another StackExchange community, and since the asker is the same he already knows the answer. Hope you're learning well! – Japsz Nov 02 '21 at 15:44

1 Answers1

0

When the page/app loads, Firebase tries to restore the user that was previously active from the credentials it persisted. This requires it to make a call to the servers though, for example to check whether the account was disabled, which means it takes some time and happens asynchronously.

In practice this means that user may be null for a few moments just after the page has loaded, even of it is then set to a value after that, and your code will have to handle that.

A simple way to do that:

<Text>Welcome Social Network {user ? user.uid : "Loading..."}</Text>
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks. This removes the error, but does not show the `uid` of the logged in user. It only shows the title and Loading ... – juan José Oct 23 '21 at 14:25
  • 1
    That sounds like the user is not being restored. It might be worth checking if that's the case with code like this: https://stackoverflow.com/a/46143694/209103 – Frank van Puffelen Oct 23 '21 at 15:00
  • I did that test and I only get error. As I said, the user is registered. If you are not registered, you cannot get to the `Home` page. See that I added the file `Routes.js` of the project, that is already contemplated. Remember we are using `@react-native-firebase` – juan José Oct 23 '21 at 15:31