Search code examples
javascriptangularfirebasegoogle-cloud-firestoreangularfire2

For Angular Material MatTable, AngularFire collection query "this.filteredData" is undefined when multiple queries are chained


...
this.db
        .collection(uid, (ref) => {
          console.log('ref', ref);
          return ref.where('year', '==', '1954').orderBy('lastName');
        })
        .snapshotChanges()
...

This produces the error:

ERROR TypeError: Cannot read properties of undefined (reading 'length')
    at MatTableDataSource._filterData (table.js:725)

When I dig into the table module in node_modules at @angular/material/ivy_ngcc/fesm2015/table.js :

 /**
     * Returns a filtered data array where each filter object contains the filter string within
     * the result of the filterTermAccessor function. If no filter is set, returns the data array
     * as provided.
     */
    _filterData(data) {
        // If there is a filter string, filter out data that does not contain it.
        // Each data object is converted to a string using the function defined by filterTermAccessor.
        // May be overridden for customization.
        this.filteredData = (this.filter == null || this.filter === '') ? data :
            data.filter(obj => this.filterPredicate(obj, this.filter));
        if (this.paginator) {
            console.log('this.filteredData', this.filteredData);
            this._updatePaginator(this.filteredData.length);
        }
        return this.filteredData;
    }

if I use .orderBy or where, or any other query by itself, this.filteredData returns the array of filtered data, as expected. But if I try to use multiple queries, as in the example above with .where().orderBy() then this.filteredData returns undefined.

Anyone have any idea why this might be?


Solution

  • I thought for sure it had something to do with where MatPagination and MatSort exist in the Angular lifecycle hooks vs when/how the data is fetched from FireStore via AngularFire.

    Nope.

    I just needed to create a composite index in FireStore Database -> Indexes. In this case containing "year" and "lastName" fields.

    It threw me off because there wasn't the traditional error with link to index it in firestore that usually is shown in this type of scenario.