reactjsfirebasegoogle-cloud-firestore

How to query using inline JSX conditional expression using Firebase?


I googled but couldn't find a similar usage. Maybe the question is very specific but I wonder if I can write an inline conditional JSX expression using firebase like this way or somewhat similar to this?

let querySnapshot = await getDocs(query(collection(db, "users"), 
    where(targetChosen === "town" ? ("town", "==", user.town) : targetChosen === "city" ? ("city", "==", user.city) :  targetChosen === "country" && ("country", "==", user.country) ),
    where("gender", "==", genderChosen),
    orderBy("rating", "desc"),
    limit(10)
))

Here an error comes:

function where() called with invalid data.
Unsupported field value: undefined.

EDIT: user is an object having fields { id: string, name: string, town: string, city: string, country: string }. targetChosen is a local variable (not depending on user object) and also a string which is one of the strings of "town", "city" or "country". genderChosen is one of the strings of "female" or "name". (it works without any problem with JSX expression when used as variable inside firebase function). The targetChosen string value is changing according to 3 buttons with titles of "town", "city" and "country". Whenever one of them clicked, targetChosen string value changes. Its structure can be changed for this aim in the question to be done, maybe translating it to a 3 itemed array for the firebase code to work.


Solution

  • As Frank said in comments, you can't use a JSX expression like this. where requires exactly three arguments, and you need to provide them in the way that JavaScript requires, just like any function call. For your case, it could go something like this, since targetChosen always matches the name of the field filter, as well as the name of the property of the user object:

    ...
    where(targetChosen, "==", user[targetChosen]),
    ...
    

    If for some reason you can no longer make the stated assumptions, and have to write some conditional based on the value of targetChosen, maybe you'll have to use a switch on the value of targetChosen to determine the values to pass to where.