首页 > 解决方案 > 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)
  }
}

标签: javascriptfirebasereact-nativegoogle-cloud-firestore

解决方案


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

`

推荐阅读