0

In the code below is it possible to conditionally render the Where statements at all (based on a variable existing)?

useEffect(() => {
        const getProducts = projectFirestore.collection(collection)
            .where("color", "==", `${urlColor}`)
            .where("size", "==", `${urlSize}`)
            .onSnapshot((snap) => {
                ...
            })

            return () => getProducts();

    },[collection])

    return { docs };
}

I'm pulling in the 'urlColor' and 'urlSize' from URL parameters but they only exist if the user selects that option. I'd like functionality like

if (urlColor && .where("size", "==", `${urlSize}`))

Any help much appreciated, Matt

Ray Purchase
  • 681
  • 1
  • 11
  • 37

1 Answers1

2

Yes, you'll just need to save a temporary variable along the way.

useEffect(() => {
  let query = projectFirestore.collection(collection)

  if (urlColor) {
    query = query.where("color", "==", `${urlColor}`);
  }

  if (urlSize) {
    query = query.where("size", "==", `${urlSize}`)
  }

  const unsubscribe = query.onSnapshot((snap => {
    ...
  });

  return () => unsubscribe();
});
Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
  • Just out of curiosity, I wonder if you would try NOT resetting `query = ` every time you add a `where`, and see if the `where` gets applied to the original object – TKoL Nov 18 '20 at 16:20
  • Laravel queries, for example, have a similar mechanism but you don't have to do `query =` every time you add a `where`, the original `query` stores everything you add on to it – TKoL Nov 18 '20 at 16:21
  • @TKoL I don't know whether `.where` mutates the object and then returns itself, or whether it makes a new one. So your suggestion may work, but i'm not sure. – Nicholas Tower Nov 18 '20 at 17:35
  • @NicholasTower Many thanks, that's worked fantastically well – Ray Purchase Nov 18 '20 at 23:52