Home > Software engineering >  How to parse the number of documents inside a collection to a variable?
How to parse the number of documents inside a collection to a variable?

Time:09-30

I want to set up a fake ID for aesthetic purposes that increases by one every time a new piece of information is created. Now in my head I have an idea such as

var = the amount of documents already in the collection 1

and there IS a way to read the number of documents inside a collection and it would be: with snap.size according to enter image description here

I don't know what I'm doing wrong so any help/tips/documentation is welcome!

EDIT Added another console.log under the console.log(size) and I'm even more confused now... because it does return the right amount is just not saving properly maybe ? idk.

enter image description here

CodePudding user response:

You're indeed setting the snap.size value to your React state. The problem is that you're making an async call (docRef2.set({ ... })) that executes before that value is set in your state. If you need to use the size value returned from the first asynchronous call in the second then you have two options:

  • Put the second call: docRef2.set({ ... }) inside the then callback for the first call and make use of the snap.size directly, without saving to state

  • Make use of async/await in the register function and make the necessary conversions

  • Related