What is the best way to retrieve a Map object from Firebase in a TypeScript environment?

Currently, I am working on a cloud function in TypeScript, where I am attempting to retrieve a Map object (also known as nested objects or maps) from Firebase in order to iterate through it.

Here is the structure of my Firebase data:

https://i.sstatic.net/clICC.png

My goal is to access the data like this:

const tokenSettingsRef = db.collection('tokenSettings').doc('spread')
transaction.get(tokenSettingsRef).then((tokenSettingsDocSnapshot) => {
    const tokenData = tokenSettingsDocSnapshot.data()
    if (typeof tokenData !== 'undefined') {
        console.log("token name 3: " + tokenData.tokens[0])
        console.log("token name 4: " + tokenData)
        console.log("token name 5: " + tokenData.tokens)
        console.log("token name 1: " + tokenData.tokens.length)
        console.log("token name 2: " + tokenData.tokens.keys())
        const variations = new Map(Object.entries(tokenData.tokens));
        console.log("token name 5: " + variations.keys)
        console.log("token name 6: " + variations.values)
    }

However, none of the approaches above are providing me with the Map I need to use or even log out. The data I am receiving appears to be something like [object Object].

I have successfully retrieved arrays and plain objects before, so I am puzzled about what I am missing here.


Answer №1

It appears that you are reading data within a transaction based on the code provided in your question. Here is a solution that should work:

var tokenSettingsRef = db.collection('tokenSettings').doc('spread');

db.runTransaction(transaction => {
    return transaction.get(tokenSettingsRef).then(tokenSettingsDocSnapshot => {

        if (!tokenSettingsDocSnapshot.exists) {
            throw "Document does not exist!";
        }

        var tokensMap = tokenSettingsDocSnapshot.data().tokens;
        //Let's print all the keys and values of the tokens map
        Object.keys(tokens).forEach(e =>
          console.log(`key=${e}  value=${tokens[e]}`)
        );
        //...... Continue the transaction
    });
}).then(function() {
    //....
})
.catch(error => {
    console.log('Transaction failed: ', error);
});

If you want to retrieve a Map<number, number> object from it, here is how you can do it:

var tokensMap = tokenSettingsDocSnapshot.data().tokens;

  const transformedTokensMap = new Map<number, number>();
  Object.keys(tokensMap).forEach(e => {
      transformedTokensMap.set(Number(e), tokensMap[e]);
});

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

Trouble with Angular 7: Form field not displaying touched status

I am encountering an issue while trying to input data into a form, as it is not registering the touched status. Consequently, an error always occurs when attempting to send a message back to the user. In my TypeScript file, I am utilizing FormBuilder to c ...

Troubleshooting: Issues with Angular 2 Dependency Injection

I am facing an issue with my angular2 application that involves a simple dependency injection, but it seems to be not working correctly. Can anyone help me figure out what might be missing? Below is the error message I am encountering: EXCEPTION: Cannot ...

Ways to use DecimalPipe for rounding numbers in Angular - Up or down, your choice!

Looking to round a number up or down using DecimalPipe in Angular? By default, DecimalPipe rounds a number like this: Rounding({{value | number:'1.0-2'}}) 1.234 => 1.23 1.235 => 1.24 But what if you want to specifically round up or do ...

Differentiating functions in Typescript through method overloading by inferring the second argument's type based on the first argument's

Looking to implement method overloading in Typescript with stricter type checking for method invocation based on different arguments. I am encountering an error: 'props' is possibly 'undefined'. This is the code that is causing the e ...

An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully tra ...

What is the best way to implement pipes and incorporate reusable action buttons in a Mat-table component for maximum reusability?

I am seeking assistance in creating a reusable component for the Angular Material Mat-table. I have made progress on loading data from the parent component to the child component, as can be seen in StackBlitz, but I now want to apply pipes to the data bef ...

Could someone provide an explanation for the meaning of the phrase "class User extends Model<UserAttribute UserCreationAttribute>"?

View Image of the Issue I am puzzled by why we are utilizing both UserCreationAttribute and UserAttribute in that specific arrow, especially when UserCreationAttribute is created by omitting one field from UserAttribute. Can someone please clarify this fo ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

Utilizing React to pass parent state to a child component becomes more complex when the parent state is derived from external classes and is subsequently modified. In this scenario,

I'm struggling to find the right way to articulate my issue in the title because it's quite specific to my current situation. Basically, I have two external classes structured like this: class Config { public level: number = 1; //this is a s ...

Error message: "Using AngularFire 2 caused an issue as Firebase is not identified as a

I am interested in creating a sample app using Ionic 2 and AngularFire 2. After successfully integrating AngularFire 2 into Ionic 2, I encountered an error while trying to retrieve data from Firebase. The error message displayed in the browser console: ` ...

Issue with ESLint error in TypeScript PrimeReact async Button click handler

I am currently facing an issue with exporting data from a DataTable in PrimeReact. The onClick function for the Button does not allow async callbacks as flagged by eslint. Can someone guide me on how to properly call this function? const exportCSV = us ...

Template specific requirements in Angular

When I have a child component app-page-header, here's what I want to achieve: If the value of headerOptions.headerTitle is not 'Idle Disposition', then set [titleData] to equal 'headerOptions.headerTitle'. However, if headerOptions ...

Stripe has encountered an error stating that the provided identifier does not correspond to any user record in the system

Encountering an error when attempting to create a "checkout_session" using the Stripe Firebase Extension with Nextauth. The error message reads: "There is no user record corresponding to the provided identifier." This issue arises after trying to push "c ...

Posting forms in NextJS can be optimized by utilizing onChange and keypress events for input fields

I am currently working on my first Edit/Update form within a newly created NextJs application as I am in the process of learning the framework. I seem to be facing an issue where the form constantly posts back to the server and causes the page to refresh ...

Is there a specific instance where it would be more appropriate to utilize the styled API for styling as opposed to the sx prop in Material-

I am currently in the process of migrating an existing codebase to Material UI and am working towards establishing a styling standard for our components moving forward. In a previous project, all components were styled using the sx prop without encounteri ...

The boolean type in TypeScript is throwing an error because it does not have any call

Currently, I am grappling with an issue in my Typescript and React Native project. The error message displayed on the console reads: "This expression is not callable. Type 'Boolean' has no call signatures." My code consists of a simple home page ...

Tips for effectively combining the map and find functions in Typescript

I am attempting to generate an array of strings with a length greater than zero. let sampleArray2:string[] = ["hello","world","angular","typescript"]; let subArray:string[] = sampleArray2 .map(() => sampleArray2 .find(val => val.length & ...

Steps for incorporating moment.js into an Angular 2 project

Having trouble importing moment.js into my angular2 application despite following various guides and solutions provided. Even though the package is present in my IDE (Visual Studio) and the moment.d.ts file is easily found, I keep encountering errors when ...

What methods can be used to display data using TypeScript's Optional Chaining feature?

I came across this Try it Yourself TypeScript Optional Chaining example in W3Schools TypeScript Null & Undefined section, and I have attached a screenshot for reference. https://i.sstatic.net/s8q1J.png The example demonstrates that when data is undef ...

Ways to effectively utilize the $getDownloadURL() promise within the ng-repeat directive in Angularjs 1.6

I am currently in the process of developing a Single Page Application (SPA) using AngularJS 1.6 along with Firebase for database and storage functionalities. One of my goals is to display an image from Firebase storage on my HTML page. I have implement ...