Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Accessing and Updating User Profile | Protecting Routes and Managing User Accounts
Firebase Authentication in React Apps

bookAccessing and Updating User Profile

When you work with Firebase Authentication in your React app, each authenticated user has a profile containing several fields. The most commonly used user profile fields are:

  • Display name: a string that represents the user's chosen name;
  • Photo URL: a link to the user's profile picture;
  • Email: the user's email address;
  • Email verified: a boolean indicating if the user has verified their email;
  • UID: a unique identifier assigned to the user;
  • Phone number: if provided, the user's phone number;
  • Provider data: an array with information about the sign-in providers used by the user.

Some of these fields, such as displayName and photoURL, can be updated by your application using Firebase's updateProfile method. The email can also be updated, but it requires the updateEmail method. Other fields, such as the UID, are set by Firebase and cannot be changed.

To display and update user profile information in your React component, you first need access to the current user object from Firebase Authentication. Usually, you get this from firebase.auth().currentUser or by using an authentication state observer. To update the user's display name or profile picture, you use the updateProfile method.

Here is a simple React component that shows the current user's display name and photo, and allows the user to update them:

import React, { useEffect, useState } from "react";
import {
  getAuth,
  onAuthStateChanged,
  updateProfile,
} from "firebase/auth";

function UserProfile() {
  const auth = getAuth();

  const [user, setUser] = useState(null);
  const [displayName, setDisplayName] = useState("");
  const [photoURL, setPhotoURL] = useState("");
  const [message, setMessage] = useState("");

  // Listen for authentication state changes
  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);

      if (currentUser) {
        setDisplayName(currentUser.displayName || "");
        setPhotoURL(currentUser.photoURL || "");
      }
    });

    return unsubscribe;
  }, [auth]);

  const handleUpdate = async (e) => {
    e.preventDefault();
    if (!user) return;

    try {
      await updateProfile(user, {
        displayName,
        photoURL,
      });
      setMessage("Profile updated successfully!");
    } catch (error) {
      setMessage("Update failed: " + error.message);
    }
  };

  if (!user) {
    return <p>Loading profile...</p>;
  }

  return (
    <div>
      <h2>User Profile</h2>

      {photoURL && (
        <img
          src={photoURL}
          alt="Profile"
          width={80}
          height={80}
          style={{ borderRadius: "50%" }}
        />
      )}

      <form onSubmit={handleUpdate}>
        <div>
          <label>
            Display Name:
            <input
              value={displayName}
              onChange={(e) => setDisplayName(e.target.value)}
            />
          </label>
        </div>

        <div>
          <label>
            Photo URL:
            <input
              value={photoURL}
              onChange={(e) => setPhotoURL(e.target.value)}
            />
          </label>
        </div>

        <button type="submit">Update Profile</button>
      </form>

      {message && <p>{message}</p>}
    </div>
  );
}

export default UserProfile;

This component displays the user's current display name and profile photo. When the user enters a new display name or photo URL and submits the form, the updateProfile method updates the Firebase user profile with the new values. You can use similar logic to update other fields, such as the email, but remember that some fields (like UID) cannot be changed.

question mark

Which of the following user profile fields can you update directly using Firebase Authentication's updateProfile method?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

Suggested prompts:

How can I update the user's email address in this component?

What should I do if the user is not authenticated?

Can you explain how to handle errors when updating the profile?

bookAccessing and Updating User Profile

Stryg for at vise menuen

When you work with Firebase Authentication in your React app, each authenticated user has a profile containing several fields. The most commonly used user profile fields are:

  • Display name: a string that represents the user's chosen name;
  • Photo URL: a link to the user's profile picture;
  • Email: the user's email address;
  • Email verified: a boolean indicating if the user has verified their email;
  • UID: a unique identifier assigned to the user;
  • Phone number: if provided, the user's phone number;
  • Provider data: an array with information about the sign-in providers used by the user.

Some of these fields, such as displayName and photoURL, can be updated by your application using Firebase's updateProfile method. The email can also be updated, but it requires the updateEmail method. Other fields, such as the UID, are set by Firebase and cannot be changed.

To display and update user profile information in your React component, you first need access to the current user object from Firebase Authentication. Usually, you get this from firebase.auth().currentUser or by using an authentication state observer. To update the user's display name or profile picture, you use the updateProfile method.

Here is a simple React component that shows the current user's display name and photo, and allows the user to update them:

import React, { useEffect, useState } from "react";
import {
  getAuth,
  onAuthStateChanged,
  updateProfile,
} from "firebase/auth";

function UserProfile() {
  const auth = getAuth();

  const [user, setUser] = useState(null);
  const [displayName, setDisplayName] = useState("");
  const [photoURL, setPhotoURL] = useState("");
  const [message, setMessage] = useState("");

  // Listen for authentication state changes
  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);

      if (currentUser) {
        setDisplayName(currentUser.displayName || "");
        setPhotoURL(currentUser.photoURL || "");
      }
    });

    return unsubscribe;
  }, [auth]);

  const handleUpdate = async (e) => {
    e.preventDefault();
    if (!user) return;

    try {
      await updateProfile(user, {
        displayName,
        photoURL,
      });
      setMessage("Profile updated successfully!");
    } catch (error) {
      setMessage("Update failed: " + error.message);
    }
  };

  if (!user) {
    return <p>Loading profile...</p>;
  }

  return (
    <div>
      <h2>User Profile</h2>

      {photoURL && (
        <img
          src={photoURL}
          alt="Profile"
          width={80}
          height={80}
          style={{ borderRadius: "50%" }}
        />
      )}

      <form onSubmit={handleUpdate}>
        <div>
          <label>
            Display Name:
            <input
              value={displayName}
              onChange={(e) => setDisplayName(e.target.value)}
            />
          </label>
        </div>

        <div>
          <label>
            Photo URL:
            <input
              value={photoURL}
              onChange={(e) => setPhotoURL(e.target.value)}
            />
          </label>
        </div>

        <button type="submit">Update Profile</button>
      </form>

      {message && <p>{message}</p>}
    </div>
  );
}

export default UserProfile;

This component displays the user's current display name and profile photo. When the user enters a new display name or photo URL and submits the form, the updateProfile method updates the Firebase user profile with the new values. You can use similar logic to update other fields, such as the email, but remember that some fields (like UID) cannot be changed.

question mark

Which of the following user profile fields can you update directly using Firebase Authentication's updateProfile method?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 3. Kapitel 3
some-alt