Skip to content

idField on valueChanges doesn't work as expected. #2753

Closed
@ammaarpatel99

Description

@ammaarpatel99

Version info

Angular: 11

Firebase: 8

AngularFire: 6

Other: MacOS Big Sur

Issue

When you call valueChanges on a document you know doesn't exist, it emits undefined. However if you specify idField, for example, as id, then it will return an object with the field id. I expected that it would still return undefined. It returning causes problems, as the object then isn't in the shape you expect (if you specify a type of the result) but also you get a result when a document doesn't actually exist.

I think the issue is simply in the valueChanges function:

valueChanges<K extends string>(options: { idField?: K } = {}): Observable<T | undefined> {
  return this.snapshotChanges().pipe(
    map(({ payload }) =>
      options.idField ? {
        ...payload.data(),
        ...{ [options.idField]: payload.id }
      } as T & { [T in K]: string } : payload.data()
    )
  );
}

As you can see, if payload.data() is undefined, this function will create an object with id field. I think a simple fix would be:

valueChanges<K extends string>(options: { idField?: K } = {}): Observable<T | undefined> {
  return this.snapshotChanges().pipe(
    map(({ payload }) =>
      options.idField && payload.data() ? {
        ...payload.data(),
        ...{ [options.idField]: payload.id }
      } as T & { [T in K]: string } : payload.data()
    )
  );
}

I don't actually know much about the underlying firebase apis, but I'm assuming that payload.data() is undefined if there is no document.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions