Home > other >  Using the spread operator on an array of filters to create a Firestore query
Using the spread operator on an array of filters to create a Firestore query

Time:09-17

I'm working on a filter component for my React web app and want to return (pass through props) an array of conditions for the Firestore query.

For example if the user wants to filter out posts with no comments, they check a checkbox and a where("commentsCount", ">", "0") is added to the array of filters.

  const queryParams = [
    collection(db, "posts"),
    orderBy(sortType, sortMethod),
    limit(POSTS_PER_PAGE),
  ];
  const filters = [
    where("commentsCount", ">", "0"),
    // And possibly more where's
  ];
  queryParams.push(...filters);
  
  // Create a firestore query object using the parameters
  const _query = query(...queryParams);

But doing this gives me a TypeScript error: A spread argument must either have a tuple type or be passed to a rest parameter. TS2556.

What am I doing wrong?

CodePudding user response:

You cannot pass an argument of type (CollectionReference<DocumentData> | QueryConstraint)[] in query. Try adding collection() directly in query and removing it from queryParams so it'll be an array of type QueryContraint[]:

const queryParams = [
  orderBy(sortType, sortMethod),
  limit(POSTS_PER_PAGE),
];

const filters = [
  where("commentsCount", ">", "0"),
  // And possibly more where's
];
  
// Create a firestore query object using the parameters
const _query = query(collection(db, "posts"), ...queryParams);
  • Related