为什么displayName无法更新?使用onAuthChanged

时间:2020-10-30 13:08:54

标签: javascript reactjs firebase-realtime-database redux firebase-authentication

我正在使用Redux并保留我的身份验证。使用redux工具包,我有一个操作可以从Firebase Auth中检查export const persistedSession = () => { return async (dispatch) => { dispatch(requestLogin()); firebaseAuth.onAuthStateChanged(async (user) => { if (user) { const currentUser = await createUserProfileDocument(user); currentUser.on("value", (snapshot) => { var data = snapshot.val(); if (data !== null) { //Success } }); } }); }; };

export const createUserProfileDocument = async (user) => {
  if (!user) return;

  const { uid, displayName, email } = user;
  const userReference = database.ref("users");
  userReference.once("value", (snapshot) => {
    if (!snapshot.hasChild(uid)) {
      userReference.child(uid).set({
       ...
      });
    }
  });
  return userReference;
};

然后,当我检查该用户的文档是否存在并且是否创建该文档时。

displayName

这就是我的问题所在。创建用户onAuthChanged时始终为空,如何正确更新用户个人资料?似乎export const registerUser = (value) => { const { firstName, surname, email, password } = value; return async (dispatch) => { firebaseAuth .createUserWithEmailAndPassword(email, password) .then(async (result) => { const user = result.user; user.updateProfile({ displayName: `${firstName} ${surname}`, }) }) .catch((error) => { console.log("Unable to create user profile: ", error); }); }; }; 已被触发,然后才能进行更新,以便displayName始终为null,并且文档将不包含displayName属性

var clientId = $("#ClientId").val();

var url = "/eventHub?ClientId=" + clientId;

var connection = new signalR.HubConnectionBuilder()
        .withUrl(url)
        .build();
    connection.on("SendCountEventToClient", function (message) {

        //console.log(message);
    });


   public interface IEventHub
   {
        Task SendCountEventToClient(ProductCountModel message);
   }

    private readonly IHubContext<EventHub> _eventHub;

    private Timer _EventGenTimer;

    public EventReceiverService(IHubContext<EventHub> eventHub)
    {
        _eventHub = eventHub;

        Init();
    }

    private void Init()
    {
        _EventGenTimer = new Timer(5 * 1000)
        {
            AutoReset = false
        };

        _EventGenTimer.Elapsed += EventGenTimer_Elapsed; ;
    }

    public void StartReceive()
    {
        _EventGenTimer.Start();
    }

    private async void EventGenTimer_Elapsed(object sender, ElapsedEventArgs e)
    {
        _EventGenTimer.Enabled = false;

        var ProductCounts = await Business.News.GetCounts(910);

        _eventHub.Clients.All.SendAsync(nameof(IEventHub.SendCountEventToClient),
            JsonConvert.SerializeObject(ProductCounts)).GetAwaiter().GetResult();

        _EventGenTimer.Enabled = true;
    }

1 个答案:

答案 0 :(得分:0)

呼叫updateProfile不会触发onAuthStateChanged,因为身份验证状态不会改变。同样,这里也没有办法延迟onAuthStateChanged的触发,因为您只能在创建用户帐户后设置显示名称,这也会对其进行登录。

我可以想到的两个选择:

  1. 创建用户,设置其显示名称,将其注销,然后再次登录。后者随后将触发另一个onAuthStateChanged ,其中包含显示名称。

  2. 当您也调用updateProfile时,也将显示名称也明确地写入数据库。