0

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

size = the number 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 How many items a collection has. So following that logic, if I'm not wrong, this should give the size:

const [size, setSize] = useState("");

const register = (e) => {
     e.preventDefault();
     const docRef1 = db.collection('usuarios').doc(user.uid).collection('estudiantes');
     const docRef2 = db.collection('usuarios').doc(user.uid).collection('estudiantes').doc();

// ------------This Bit-----------------     
     docRef1.get().then(snap => {
       var tempSize = snap.size
       ++tempSize;
       console.log(snap.size)
       console.log(tempSize)
       setSize (tempSize)
       console.log(size)
       console.log(tempSize)
     })
// --------------------------------------      
     docRef2.set({
       nombre: firstName + " " + lastName,
       colegio: escuela,
       grado: grado,
       uid: docRef2.id,
       id: size

     }).then((r) => {
         history.push("/Inicio");
     })
   }

and it does bring me back the size of the collection properly BUT when I parse the data to the variable, but when I want to use (in this case size) it says the value is null.

(Example from a 0 docs collection)

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

JayCodist
  • 2,424
  • 2
  • 12
  • 28
ReactPotato
  • 1,262
  • 3
  • 26
  • 46

1 Answers1

2

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

JayCodist
  • 2,424
  • 2
  • 12
  • 28
  • I did the first one and didn't work :c I think I did it correctly will update it on the question. Gonna try second approach. – ReactPotato Sep 30 '21 at 02:01
  • 1
    You were supposed to use the size value directly in your second call. Not from state since you can't use the updated state value in the same function where you made the update. You should do `id: tempSize` instead – JayCodist Sep 30 '21 at 04:21
  • Yeah that worked! thank you very much – ReactPotato Sep 30 '21 at 04:25