首页 > 解决方案 > Firebase set user from auth to firestore

问题描述

I want to set user from auth to database. I do it by .set and it is working good but if I have some fields for one user, then all data are reset when user will sign in again. For this example collection -> users -> docs: (name, color). The name will be static after login but color could be changing and remember to the next logging. On the login I set:

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));
  }

And in another file when the user clicks on the setting and changes his color is also changing in the database, but when he login again the function signIn reset this color.

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

So question is how to check if(userExist)/ filter or sth like this between .doc(result.user.uid) and set(). I tried to do this by .where in firebase, setting data to reducer but always was the same result, so I decide to ask you.

标签: javascriptreactjsfirebasegoogle-cloud-firestore

解决方案


If I correctly understand your question, you should query for the user doc in the signIn() function, in order to check if it already exists or not, as follows:

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));
  }

推荐阅读