3

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>
2
  • Can you share code of your setUserInformation() function? I would like to confirm if you are using updateProfile anywhere in that. Commented Dec 12, 2021 at 4:18
  • @Dharmaraj I updated my code, my setUserInformation() is in App.js and passed into the CreateUser function on my CreateUserPage.js Commented Dec 12, 2021 at 18:36

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.