Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to query data from Firestore with dynamic input [duplicate]

I have a problem with my code and I don't know how to solve it in the correct way.

I am trying to write a filter that when user clicks on each filter, it will automatically query the data from firestore.

enter image description here

In my Redux Saga have this one:

const {type, currency, location} = action.payload;

All is work fine but the thing is when I trying to query the data with dynamic input: For example:

firebase
        .firestore()
        .collection("ItemData")
        .where("type", "==", type)
        .where('currency', '==', currency)
        .where('location', '==', location)

When user clicks on option type it shows nothing as the input currency and location have no data, just the empty string, so the query return none response. Unless you click all the filter it will show the correct response.

So how can I solve that problem?

like image 309
Tony Bui Avatar asked Jan 20 '26 10:01

Tony Bui


1 Answers

You should only add to the query clause when needed (ie. type, currency, or location are true/not empty):

let query = firebase
    .firestore()
    .collection("ItemData");

if (type) {
    query = query.where('type', '==', type);
}

if (currency) {
    query = query.where('currency', '==', currency);
}

if (location) {
    query = query.where('location', '==', location);
}

Special thanks to this post which had a similar issue to yours.

like image 180
ugh StackExchange Avatar answered Jan 22 '26 23:01

ugh StackExchange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!