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)
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.