javascript - 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.
解决方案
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));
}
推荐阅读
- android - 多模块项目:如果不覆盖,使用哪些模块资源?
- sql - 在递归查询中对结果进行排序
- laravel - 删除特殊字符和空白字符
- javascript - 如何使用 React 创建具有条件可编辑输入/单元格的表格?
- mysql - 为多语言内容设置数据库的最实用方法是什么?
- azure-web-app-service - 如何将静态资产从 VSTS 部署到多个应用程序?
- java - 有没有办法在所有spring上下文初始化后调用bean中的方法
- javascript - 反应操纵 NumberFormat 格式以有条件地工作
- django - “pip install mysqlclient”需要 microsoft visual c++ 错误
- ios - 使用 CALayer 绘制可动画的激光束