javascript - Cant find variable - parameter add function with firestore
问题描述
Im a novice in react native, Im trying to retrieve the email of the User connected (emailUser), to add it in the collection Tasks in firestore
Im getting the error "Can't find the variable emailUser" when Im trying to add it in the firestore database
addTask=async(task,categ)=>{
var useruid=firebase.auth().currentUser.uid;
await firebase.firestore().collection("Users").doc(useruid).get().then(documentSnapshot=>{
const emailUser=documentSnapshot.data().email;
console.log("email = " + emailUser)
})
try{
await firebase.firestore().collection("Tasks").where('task','==',task).where("User",'==',useruid).get().then(documentSnapshot=>{
{
console.log('Task exists : ',documentSnapshot.docs.length>0)}
if(documentSnapshot.docs.length>0)
{
alert('This task already exists')}
else
{
firebase.firestore().collection('Tasks').add({User:emailUser,task:task,category:categ})
.then(alert('Task added!'));
this.setState((state,props)=>
({
tasks:[...state.tasks,task],
}),()=>{
console.log(this.state);
});
}
})
}
catch(error)
{
console.log("error = "+error)
}
}
解决方案
You can't use userEmail
out of then callback you need do some changes on your code please try like this
addTask = async (task, categ) => {
var useruid = firebase.auth().currentUser.uid;
const docSnap = await firebase
.firestore()
.collection('Users')
.doc(useruid)
.get();
const emailUser = docSnap.data().email;
try {
await firebase
.firestore()
.collection('Tasks')
.where('task', '==', task)
.where('User', '==', useruid)
.get()
.then((documentSnapshot) => {
{
console.log('Task exists : ', documentSnapshot.docs.length > 0);
}
if (documentSnapshot.docs.length > 0) {
alert('This task already exists');
} else {
firebase
.firestore()
.collection('Tasks')
.add({ User: emailUser, task: task, category: categ })
.then(alert('Task added!'));
this.setState(
(state, props) => ({
tasks: [...state.tasks, task],
}),
() => {
console.log(this.state);
},
);
}
});
} catch (error) {
console.log('error = ' + error);
}
};
`
推荐阅读
- c++ - c++11前类lambda函数数组字典
- android - 如何正确限制这些图像?
- javascript - react useEffect 获取数据已完成但返回值未定义
- python - 我的代码抛出关于 NoneType 的错误,但应该定义它
- java - Istio,gRPC,没有获得服务器跨度跟踪
- vb.net - 在 MVC5 控制器中,如何为 HtmlHelper 的 htmlAttributes 或 routeValues 创建 IDictionary 或 routeValueDictionary?
- c++ - 成员函数模板,用于在具有任意参数的数据成员上调用函数
- reactjs - 执行后操作:未处理的拒绝(错误):操作可能没有未定义的“类型”属性。你有没有拼错一个常数?
- javascript - 如何使用 jsx 短语连接对 html 的反应
- mysql - MySQL - 通过仅将源表中的一行聚合值附加到主机表上的每个选定行来加入