You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

firebase.auth().onAuthStateChanged返回值及用户属性访问问题

Understanding firebase.auth().onAuthStateChanged Return Value & User Property Issues

What's the Return Value?

From the type hint you shared, onAuthStateChanged returns a firebase.Unsubscribe function. This function exists to stop listening for auth state changes—when you call it, the callback you registered will no longer trigger when the user's auth status changes.

A common use case for this is cleaning up listeners in single-page apps, like when a component unmounts to avoid memory leaks:

// Set up the listener and capture the unsubscribe function
const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
  // Handle state changes here
});

// Later, when you no longer need the listener (e.g., component unmount)
unsubscribe();

Why Can't You Access user.uid?

The problem is that user can be null! When no user is logged in, the onAuthStateChanged callback will receive null as its parameter—Firebase triggers this callback immediately when you set up the listener, regardless of whether a user is signed in or not.

Your original code didn't check if user exists before accessing user.uid, which leads to errors like Cannot read property 'uid' of null.

Fix: Check for User Existence First

You need to verify that user isn't null before accessing its properties. Here's the corrected code:

firebase.auth().onAuthStateChanged((user) => {
  console.log("data from stateChanged: ", user);
  
  // Confirm a user is logged in first
  if (user) {
    // Now you can safely access user properties
    console.log("User UID:", user.uid);
    console.log("User Email:", user.email);
  } else {
    // Handle the logged-out state
    console.log("No user is currently signed in.");
  }
});

Note: Even though the type hint shows the callback parameter as firebase.User, in practice it can be User | null. This is a quirk in Firebase's type definitions, but the runtime behavior always includes the possibility of null, so the null check is non-negotiable.

内容的提问来源于stack exchange,提问作者Noman

火山引擎 最新活动