Home > Software engineering >  ReactJS firebase auth displayName return null
ReactJS firebase auth displayName return null

Time:12-13

Im working on a ReactJS app and integrated Firebase's authentication for the create user and login functionalities. Im having trouble figuring out how to set displayName because every account I create has a displayName of "null". This is my function for creating a user account. I went thorough the Firebase documentation and could only find out to get displayName but not how to set it?

function CreateUser({ setUserInformation, setErrors, setLoggedIn }) {
  const signUpUser = useCallback(
    (e) => {
      e.preventDefault();

      const email = e.currentTarget.email.value;
      const password = e.currentTarget.password.value;
      const displayName = e.currentTarget.displayName.value;
      // const displayName = document.getElementById("name").value;
      const auth = getAuth();

      createUserWithEmailAndPassword(auth, email, password)
        .then((userCredential) => {
          // Signed in
          const user = userCredential.user;
          setLoggedIn(true);
          setUserInformation({
            email: user.email,
            displayName: user.displayName,
            uid: user.uid,
            accessToken: user.accessToken,
          });
          setErrors();
        })
        .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          console.warn({ error, errorCode, errorMessage });
          setErrors(errorMessage);
        });
    },
    [setErrors, setLoggedIn, setUserInformation]
  );

My App.js:

function App() {
  // Track if user is logged in
  const [loggedIn, setLoggedIn] = useState(false);
  // check to see if there is any loading...
  const [loading, setLoading] = useState(true);
  //store user information in state
  const [userInformation, setUserInformation] = useState({});
  const [appInitialized, setAppInitialized] = useState(false);
  // Error
  const [errors, setErrors] = useState();

  // Ensure app is initialized when it is ready to be
  useEffect(() => {
    // initialized firebase
    initializeApp(FirebaseConfig);
    setAppInitialized(true);
  }, []);

  // check to see if user is logged in
  // user loads page, check their status
  // set state accordingly
  useEffect(() => {
    if (appInitialized) {
      const auth = getAuth();
      onAuthStateChanged(auth, (user) => {
        if (user) {
          //user is signed in
          setUserInformation(user);
          setLoggedIn(true);
        } else {
          // user is signed out
          setUserInformation({});
          setLoggedIn(false);
        }
        // whenever state cxhanges setLoading to false
        setLoading(false);
      });
    }
  }, [appInitialized]);

  function logout() {
    const auth = getAuth();
    signOut(auth)
      .then(() => {
        setUserInformation({});
        setLoggedIn(false);
        setErrors();
      })
      .catch((error) => {
        console.warn(error);
        setErrors(error);
      });
  }

  if (loading || !appInitialized) return null;

  return (
    <div>
      <Header
        logout={logout}
        loggedIn={loggedIn}
        userInformation={userInformation}
      />
      <Router>
        <Routes>
          <Route
            path="/login"
            element={
              !loggedIn ? (
                <Login
                  setErrors={setErrors}
                  setLoggedIn={setLoggedIn}
                  setUserInformation={setUserInformation}
                />
              ) : (
                <Navigate to="/" />
              )
            }
          />
          <Route
            path="/create-user"
            element={
              !loggedIn ? (
                <CreateUser
                  setLoggedIn={setLoggedIn}
                  setUserInformation={setUserInformation}
                  setErrors={setErrors}
                />
              ) : (
                <Navigate to="/" />
              )
            }
          />
        </Router>

CodePudding user response:

When a new user registers, you would have to update their display name using updateProfile() method as shown below:

const displayName = e.currentTarget.displayName.value;

createUserWithEmailAndPassword(auth, email, password)
  .then(async (userCredential) => {
    //  ^^^^^ async function 
    // Signed in
    const user = userCredential.user;
    setLoggedIn(true);

    // Updating user name
    await updateProfile(auth.currentUser, { displayName })

    setUserInformation({
      displayName,
      email: user.email,
      uid: user.uid,
      accessToken: user.accessToken,
    });
    setErrors();
  })

Now user.displayName should be updated. Checkout the documentation for more information.

  • Related