Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Los datos siempre registran 0 si registran la longitud cuando obtienen datos de firestore

Estoy tratando de obtener datos de firestore, mi flujo de trabajo es así:

  • Cree una matriz, luego registre la identificación de la colección de 'usuarios'

  • Verifique si el usuario existe al verificar si el valor existe en la matriz anterior, si existe, luego inicie sesión directamente, si no, cree una nueva colección en firestore

Pero no sé cómo cuando registro los datos, se muestran correctamente, pero si registro la longitud, siempre muestra 0 y, por supuesto, la comparación muestra falso cada vez.

Aquí está el código

 export default function Login(props: LoginI) { const user = useRef<User>(); const [userExist, setUserExist] = useState<boolean>(false); let ListUser: any[] = []; const {} = props; const addNew = () => { firestore() .collection("Users") .doc(user.current?.user?.email) .set({ userInfo: { ...user.current }, note: firebase.firestore.FieldValue.arrayUnion(), }); // .then(() => console.log("success")); }; const getUser = async () => { await firebase .firestore() .collection("Users") .get() .then((data) => { data.forEach((snapshot) => { ListUser.push(snapshot.id); ====> //add user to local array }); }); }; async function signIn() { // Get the users ID token const userInfo = await GoogleSignin.signIn(); user.current = userInfo; getUser(); console.log("firebaseList", ListUser); ==> always return value console.log("firebaseList", ListUser.length); ==> alway return 0 // ListUser = ListUser.concat(user.current.user?.email); ListUser.forEach((item) => { console.log("item", item); if (item === user.current?.user?.email) { setUserExist(true); return; } return; }); console.log(userExist); // Create a Google credential with the token const googleCredential = auth.GoogleAuthProvider.credential( userInfo.idToken ); // Sign-in the user with the credential return auth().signInWithCredential(googleCredential); } return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Button onPress={() => { signIn(); }} > <Text style={{ color: "white" }}>Login</Text> </Button> </View> ); }

Aquí está la foto de este ingrese la descripción de la imagen aquí

no se donde me equivoque ayuda por favor muchas gracias

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Está llamando a una base de datos distante en su función getUser (en este caso, base de firebase ), una solicitud de red que inevitablemente llevará más tiempo ejecutar que su código local.

Esto lleva a un problema llamado condición de carrera . El código debajo de su llamada a getUser() podría ejecutarse antes de que se complete la solicitud de red, lo que daría como resultado un comportamiento impredecible.

Para evitar esto, debe esperar a que se complete la llamada de red antes de continuar con las instrucciones. Ya sea que lo haga a través de callbacks de llamada, promises o sintaxis async/await depende de sus preferencias, pero dado que ya usa async/await , debe await su llamada a getUser() , a continuación se muestra su código con la corrección:

 export default function Login(props: LoginI) { const user = useRef<User>(); const [userExist, setUserExist] = useState<boolean>(false); let ListUser: any[] = []; const {} = props; const addNew = () => { firestore() .collection("Users") .doc(user.current?.user?.email) .set({ userInfo: { ...user.current }, note: firebase.firestore.FieldValue.arrayUnion(), }); // .then(() => console.log("success")); }; const getUser = async () => { await firebase .firestore() .collection("Users") .get() .then((data) => { data.forEach((snapshot) => { ListUser.push(snapshot.id); ====> //add user to local array }); }); }; async function signIn() { // Get the users ID token const userInfo = await GoogleSignin.signIn(); user.current = userInfo; // the line below was missing an await await getUser(); console.log("firebaseList", ListUser); ==> always return value console.log("firebaseList", ListUser.length); ==> alway return 0 // ListUser = ListUser.concat(user.current.user?.email); ListUser.forEach((item) => { console.log("item", item); if (item === user.current?.user?.email) { setUserExist(true); return; } return; }); console.log(userExist); // Create a Google credential with the token const googleCredential = auth.GoogleAuthProvider.credential( userInfo.idToken ); // Sign-in the user with the credential return auth().signInWithCredential(googleCredential); } return ( <View style={{ flex: 1, justifyContent: "center", alignItems: "center" }}> <Button onPress={() => { signIn(); }} > <Text style={{ color: "white" }}>Login</Text> </Button> </View> ); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!