What is the process for importing Firestore types into the utils file?

In the current logic, there is a function that handles specific data record processing stored in firestore:

private listenUserData (): void {
    this.unListenUserData = FirebaseDb
      .collection(`users`).doc(this.user.id)
      .collection(`userData`)
      .onSnapshot({ includeMetadataChanges: true }, (querySnapshot) => {
        const changes = getUserDataSnapshotChanges(querySnapshot)
        const { data, changeType } = changes

        data.config && this.handleConfigChanges(data.config, changeType)
        data.personalData && this.handlePersonalDataChanges(data.personalData)
      })
  }

This function uses a utility that processes the querySnapshot and returns an object:

export function getUserDataSnapshotChanges (querySnapshot: any): UserDataSnapshotChangesType {
  const changes: UserDataSnapshotChangesType = {
    data: {},
    changeType: ``,
    isEmpty: querySnapshot.empty
  }

  querySnapshot.docChanges().forEach((docChange: any) => {
    const { doc } = docChange

    changes.data[doc.id] = doc.data()
    changes.changeType = docChange.type
  })

  return changes
}

Currently, the QuerySnapshot and docChange use the any type. Attempts to import DocumentChange from 'firebase' have not been successful.

I have investigated the index.d.ts of firebase and found that the following type belongs to the namespace firebase.firestore: https://i.sstatic.net/QiOny.jpg

If anyone has ideas regarding this situation, I would greatly appreciate it:
1. Does this mean there is no way to import that type if it's part of a non-exported namespace?
2. If not, what could be a possible approach to access firestore for type-safe code?

Answer №1

For the creation of your FirebaseDb instance, it is recommended to use the firebase.firestore() method. The types should be accessible within the firebase.firestore namespace.

The type for querysnapshot is firebase.firestore.QuerySnapshot https://firebase.google.com/docs/reference/js/firebase.firestore.QuerySnapshot

The type for docChange is

firebase.firestore.DocumentChange
https://firebase.google.com/docs/reference/js/firebase.firestore.DocumentChange

export function getUserDataSnapshotChanges (querySnapshot: firebase.firestore.QuerySnapshot): UserDataSnapshotChangesType {
  const changes: UserDataSnapshotChangesType = {
    data: {},
    changeType: ``,
    isEmpty: querySnapshot.empty
  }

  querySnapshot.docChanges().forEach((docChange: firebase.firestore.DocumentChange) => {
    const { doc } = docChange

    changes.data[doc.id] = doc.data()
    changes.changeType = docChange.type
  })

  return changes
}

This approach works well for me in accessing Firebase types.

UPDATE

I cannot confirm the version of your Firebase node module, but this implementation was successful with version 7.13.

If you only need to import the classes, these imports can be used.

import {QuerySnapshot, DocumentChange} from '@firebase/firestore-types';

Then, utilize them as shown below.

export function getUserDataSnapshotChanges (querySnapshot: QuerySnapshot): UserDataSnapshotChangesType {
  const changes: UserDataSnapshotChangesType = {
    data: {},
    changeType: ``,
    isEmpty: querySnapshot.empty
  }

  querySnapshot.docChanges().forEach((docChange: DocumentChange) => {
    const { doc } = docChange

    changes.data[doc.id] = doc.data()
    changes.changeType = docChange.type
  })

  return changes
}

Hopefully, this solution resolves your issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: Element type is invalid: a string was anticipated, but not found

I recently experimented with the example provided in React's documentation at this link and it functioned perfectly. My objective now is to create a button using material-ui. Can you identify what is causing the issue in this code? import * as R ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Showing key-value pairs from an array of objects using Angular TypeScript

Within my angular application, I am fetching a dynamic list of objects from an API. A sample of the data structure is as follows: [ { "_id": "some id", "DATE": "2021/01/08", "COUNT&qu ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

For editing values that have been dynamically inserted

In my JSON data, there is a variable named address that contains multiple objects (i.e., multiple addresses). I am displaying these multiple addresses as shown in the following image: https://i.sstatic.net/1AG34.png When clicking on a specific address ( ...

Retrieve a specific data point from a web API using Angular framework

Objective: How can I retrieve the specific value "test" in Angular? Issue: An error message is being displayed. Error: SyntaxError: Unexpected token e in JSON at position 1 at JSON.parse () Which syntax element am I missing? ASP.NET // Retrieve "tes ...

Unable to locate the necessary file. - Implementing TypeScript in a React application

Attempting to integrate TypeScript into an existing React app by following the steps outlined at: https://create-react-app.dev/docs/adding-typescript I've followed all the instructions but encountered the following error upon trying to launch the app ...

Implementing Firebase pagination alongside Mui-Datatable pagination and sorting capabilities

I've been trying to implement server-side pagination and filtering for the Mui-Datatable to display my data, but I haven't been successful so far. Here are the snippets of code that I have been working on: One issue that I'm facing is that ...

How to access an element through the router-outlet in Angular 6?

<side-navigation [navigationTitle]="navTitle"></side-navigation> <router-outlet> </router-outlet> Within my project, I have a navigation bar located in the root component. I have set up [navigationTitle] as an @Input Decorator wit ...

Encountering Error: Cannot find Property xxx on type xxx during Angular 6 Build

My project has an unusual issue where it builds and runs perfectly, but when attempting to build it on the SYS server, I encounter the following error: ERROR in (html) Property 'ExampleDate' does not exist on type 'ExampleComponent'. ( ...

How can I handle the different data type returned by ReactDom.render?

My main focus is on rendering Markdown. Additionally, I also need to parse HTML which is passed as a string. In this scenario, children represents the HTML passed as a string, while isParseRequired indicates if parsing is needed. import cx from 'clas ...

Ways to expand a TypeScript interface and make it complete

I'm striving to achieve the following: interface Partials { readonly start?: number; readonly end?: number; } interface NotPartials extends Partials /* integrate Unpartialing in some way */ { readonly somewhere: number; } In this case, NotPar ...

Ionic app experiencing a CORS dilemma post-build

Using Ionic 3, I have written a provider code to fetch data from an API endpoint hosted on an HTTPS server. For example, my endpoint is located at . Below is the code for my provider: // Provider Class Function load(){ if(this.data){ return Pro ...

Tips for clearing an observable in Angular version 4

In the code snippet below, an observable has been created: private permissionSubject = new Subject<any>(); permissionObservable$ = this.permissionSubject.asObservable(); constructor( public apiService: ApiService) { } updatePermissionsDat ...

Arranging Data in Arrays using Angular 4 GroupBy Feature

I'm working with an array structured like this: var data = [ { student: "sam", English: 80, Std: 8 }, { student: "sam", Maths: 80, Std: 8 }, { student: "john", English: 80, Std: 8 }, { student: "j ...

Tabs in React display tab content vertically below each other when switching between tabs

I am currently working on creating Tabs using react-tabs. The tab contents are being displayed one after another (on different tabs) as shown below Here is the code snippet: <Tabs className="tabs"> <TabList className="tab-heade ...

Generate types based on properties of a nested interface dynamically

Consider the setup provided: enum FormGroups { customer = 'customer', address = 'address', } interface Customer { 'firstName': string; } interface Address { 'street': string; } interface SomeFormEvent { ...

When utilizing a property on "this" within a function defined in a constructor, the compiled JavaScript code produces an undefined result

Currently, I am in the process of creating a prototype where my objective is to develop a webservice using the express framework in TypeScript, compile it to TS, and host it within a firebase functions environment. The code structure includes a Controller ...

Angular2 Navigation Menu

I have a side bar and I want its children to appear when the user clicks on the parent. For example, clicking on LinkTest should display its corresponding content as block. You can check out the Angular and Typescript code snippet at this link: http://jsfi ...

Dynamic URL used in TRPC queries`

Is there a way to query a single post in TRPC and Next JS based on a dynamic url without using SSR or SSG? I have tried adding as string to router.query.id but encountered a TRPC error (only happening during the first load) because router.query.id is ini ...