簡體   English   中英

Firebase 將用戶從 auth 設置為 firestore

[英]Firebase set user from auth to firestore

我想將用戶從身份驗證設置為數據庫。 我是按.set 做的,效果很好,但是如果我有一個用戶的一些字段,那么當用戶再次登錄時,所有數據都會重置。 對於此示例集合 -> 用戶 -> 文檔:(名稱,顏色)。 登錄后名稱將為 static,但顏色可能會發生變化,請記住下一次日志記錄。 在我設置的登錄名中:

const signIn = () => {
    auth
    .signInWithPopup(provider)
    .then(result => {
      dispatch({
        type: actionTypes.SET_USER,
        user: result.user
      });
      db.collection('users').doc(result.user.uid)
      .set({
        name: result.user.displayName,
        color: 'blue'
      })
      // add user list
      db.collection('users').onSnapshot(snapshot => (
        dispatch({
          type: actionTypes.SET_USER_LIST,
          payload: (
            snapshot.docs.map(doc => ({
              data: doc.data()
            }))
          )
        })
        
      ))

    })
    .catch(error => alert(error.message));
  }

在另一個文件中,當用戶單擊設置並更改其顏色時,數據庫中的顏色也在發生變化,但是當他再次登錄時,function 登錄重置此顏色。

  const changeColor = e => {
    let colorVal = e.target.value;
    db.collection('users').doc(user.uid).update({
      color: colorVal
    })
    setOpenColors(!openColors)
  };

所以問題是如何在.doc(result.user.uid)和set()之間檢查if(userExist)/過濾器或類似的東西。 我嘗試在 firebase 中通過.where 執行此操作,將數據設置為減速器但始終是相同的結果,所以我決定問你。

如果我正確理解了您的問題,您應該在signIn() function 中查詢用戶文檔,以檢查它是否已存在,如下所示:

const signIn = () => {
    auth
    .signInWithPopup(provider)
    .then(result => {
      dispatch({
        type: actionTypes.SET_USER,
        user: result.user
      });

      db.collection('users').doc(result.user.uid)get()
       .then((doc) => {
         if (!doc.exists) {
            return db.collection('users').doc(result.user.uid)
              .set({
                 name: result.user.displayName,
                 color: 'blue'
            });
         } else {
            return null;
         }
       })
       .then(() => {
         db.collection('users').onSnapshot(snapshot => (
             dispatch({
                type: actionTypes.SET_USER_LIST,
                payload: ( snapshot.docs.map(doc => ({data: doc.data()})))
              })
         })
       })
       .catch(error => alert(error.message));
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM