Javascript Firebase将用户从身份验证设置为firestore
我想将用户从身份验证设置为数据库。我是通过.set来完成的,它工作得很好,但若我有一个用户的一些字段,那个么当用户再次登录时,所有数据都会被重置。对于此示例,集合->用户->文档:(名称、颜色)。登录后名称将是静态的,但颜色可能会改变,请记住下次登录。 在我设置的登录名上:Javascript Firebase将用户从身份验证设置为firestore,javascript,reactjs,firebase,google-cloud-firestore,Javascript,Reactjs,Firebase,Google Cloud Firestore,我想将用户从身份验证设置为数据库。我是通过.set来完成的,它工作得很好,但若我有一个用户的一些字段,那个么当用户再次登录时,所有数据都会被重置。对于此示例,集合->用户->文档:(名称、颜色)。登录后名称将是静态的,但颜色可能会改变,请记住下次登录。 在我设置的登录名上: const signIn = () => { auth .signInWithPopup(provider) .then(result => { dispatch({
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));
}
在另一个文件中,当用户单击设置并更改其颜色时,数据库中的颜色也在更改,但当他再次登录时,函数signIn重置此颜色
const changeColor = e => {
let colorVal = e.target.value;
db.collection('users').doc(user.uid).update({
color: colorVal
})
setOpenColors(!openColors)
};
所以问题是如何在.doc(result.user.uid)之间检查(userExist)/filter或类似的东西
和set()。我试着这样做。在firebase中,将数据设置为reducer,但结果始终相同,因此我决定询问您。如果我正确理解您的问题,您应该在
signIn()
函数中查询用户文档,以检查它是否已经存在,如下所示:
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));
}
帮助您解决这个问题的快速问题:为什么每次用户登录时都要在用户中设置值?您可以假设这些值在用户注销和重新登录之间不会发生变化,对吗?