How to query the same data with different property

Viewed 46

I have some User in Firestore like:

accountType: 'Owner',
name: 'himel',
email:'himel12@gmail.com'

And I have 20 users in DB.

I wanna do a search query based on a users name or email like:

userRef.where("name", "==", "himel").get();

or

userRef.where("email", "==", "himel12@gmail.com").get()

I am using react and useState for storing the input value

const [userQuery,setUserQuery] = useState('');

But by doing this i don't know if user writting a name or email to fetch user based on that value.

Is it possible to make single query for the user using name or email

1 Answers

You can do that in firebase, if i get what you've asked correctly try this:

 import {useState} from 'react'
 const FetchUser = ()=>{
 const [userQuery,setUserQuery] = useState('');
 const [result, setResult] = useState([])
  // you can run this based on a user event for example if the user clicks the button
  userRef.where("name", "==", userQuery).get().then(snapshot=>{
       setResult(snapshot.docs.map(doc=>({id: doc?.id, data: doc?.data()})))
  }).then(()=>{
       // if the results length is zero try by email
       if(result?.length===0){
           userRef.where("email", "==", userQuery).get().then(snapshot=>{
               setResult(snapshot.docs.map(doc=>({id: doc?.id, data: doc?.data()})))
          })  
      }
  })
  .....
  console.log(result)
  .....
 }

I hope this will give you a clue Good Luck.

Related