简体   繁体   中英

Why is firestore where clause not working with state?

I am trying to filter documents from firestore using where clause in react js. However when i use a state variable in the where clause it is not working but when i provide an actual string it starts working

Not working

firebase.firestore().collection('Partners')
    .where("Email",'==',this.state.currentUser).get().then( querySnapshot => {
      querySnapshot.forEach(doc => {

        this.setState({
          Theatre:doc.data().Theatre
        })

    })
})

working

firebase.firestore().collection('Partners')
    .where("Email",'==',"test@test.com").get().then( querySnapshot => {
      querySnapshot.forEach(doc => {

        this.setState({
          Theatre:doc.data().Theatre
        })

    })
})

Any help would be appreciated. Thank you.

EDIT I even tried console.log(this.state.currentUser==='test@test.com') and it is coming true. Yet the where clause is not working with the state variable

Might be the problem with your state variable, like async effects of setState or any other possible reasons.

Make sure your state variable currentUser has a value. For that safety, run this function in an if condition:

if(this.state.currentUser){
 firebase.firestore().collection('Partners')
     .where("Email",'==',this.state.currentUser).get().then( querySnapshot => {
       querySnapshot.forEach(doc => {

         this.setState({
           Theatre:doc.data().Theatre
         })

     })
 })
}

For debugging, try console logging it.

React state is asynchronous you do get a state value in a console but by the time firestore query is ran because it is also asynchronous your state is somehow getting override or maybe your the page is getting refreshed and state is being set again.

I had this same issue and then I checked my page was getting refreshed and I was losing the state I set even though I did got it inside the console.log() but by the time my firestore where query ran there was not state.

You need to provide the whole code here in order for us to take a look at it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM