1

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?

Tony Bui
  • 1,231
  • 7
  • 18

1 Answers1

9

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.

Blue
  • 22,608
  • 7
  • 62
  • 92
  • But how I can do the combine query like type and currency have value? – Tony Bui Dec 30 '18 at 02:35
  • 1
    @TonyBui That code should do what you want. For example, if they've selected a filter for type, it will filter down and select a type, otherwise it wont search type at all. – Blue Dec 30 '18 at 02:39
  • Ah yes. I understand what you mean. Thanks mate! 1 vote for you mate – Tony Bui Dec 30 '18 at 02:45