Home > database >  Firebase V9 with React Native - Display Name updating too slow
Firebase V9 with React Native - Display Name updating too slow

Time:02-12

I am new to react, firebase and stack overflow so please bear with me. I'm trying to create a user registration form with firebase that includes a 'name' input. It does work to update the display name, but not fast enough to show the name when the user first logs in. I need to save the homescreen.js file and then the display name populates.

code from registerscreen.js

 const [name, setName] = useState('')

const handleRegister = async () => {
if (confirmPass !== password){
  alert('Passwords Do Not Match')
  return false}
  else{
}
try{ 
const user = await createUserWithEmailAndPassword(auth, email, password)
updateProfile(auth.currentUser, {displayName: name}) 
console.log('logged in with', user.email)
} catch (error) {
    alert(error.message);
}

and here is the text on the homescreen.js to display the users name:

 <Text style={styles.text}>Logged in as {auth.currentUser?.displayName}</Text>

CodePudding user response:

Just like createUserWithEmailAndPassword, the call to `updateProfile is an asynchronous call, so you'll want to await until it's done:

await updateProfile(auth.currentUser, {displayName: name}) 

CodePudding user response:

I think you have two good options.

  1. Save the user's display name locally when they register, for example in Context or AsyncStorage, and use that on your logged-in screen. In AsyncStorage, that would look something like this:
  // registerscreen.js
  await AsyncStorage.setItem('name', name);

  // homescreen.js body
  const name = await AsyncStorage.getItem('name');
  // homescreen.js return
  <Text style={styles.text}>Logged in as {auth.currentUser?.displayName || name}</Text>

Docs for AsyncStorage are here.

  1. Show a loading indicator until your Firebase request comes back with the display name.
  // homescreen.js body
  // get auth object, however you are doing this already
  const auth = await getAuth();
  // homescreen.js return
  return (
   auth?.currentUser
     ? // your current component here
     : <LoadingScreen />
  );

LoadingScreen could be something like

  <View style={[StyleSheet.absoluteFill, { justifyContent: 'center', alignItems: 'center'>
    <LoadingIndicator />
  </View>
  • Related