I'm trying to build a firestore query conditionally but I'm getting a typescript error and I don't know what I'm missing. Below is my code.
const getInitialData = ({ collection, orderClause }: ICollection) => {
let query = app.collection(collection);
if (orderClause) {
query = query.orderBy(orderClause.value, orderClause.direction);
}
query.get().then((response) => {
const genericData: T[] = [];
response.forEach((doc) => {
genericData.push(dataResolver(doc));
});
setData(genericData);
});
};
I'm getting the error "Type 'Query' is missing the following properties from type 'CollectionReference': id, parent, path, doc, addts(2739)" when updating the query inside the if statement.
Thanks in advance!
CodePudding user response:
app.collection
returns a CollectionReference object. query.orderBy
returns a Query object. You can't assign a Query object to a CollectionReference. However, Query is a subclass of CollectionReference as you can see in the API documentation. What you can do here is make sure that your query variable is typed as a Query instead of the inferred CollectionReference so that it can hold references for either type without casting.
let query: Query = app.collection(collection);