Tengo un componente Vue llamado getDocument que obtiene un documento de Firebase.
El código dentro de la devolución de llamada onSnapshot se ejecuta de forma asíncrona. Y estoy tratando de actualizar el document y las referencias de error con los valores devueltos desde onSnapshot .
Pero quiero evitar usar un Watch fuera de getDocument si es posible, porque siempre tener que envolver mi código en un Watch es una molestia.
En su lugar, quiero poner un reloj dentro de getDocument.ts y hacer que actualice el document y las referencias de error allí.
Esto es lo que tengo hasta ahora, sin Watch dentro getDocument.ts .
src/composable/getDocument.ts
import { ref, watchEffect, watch } from 'vue'; import { db } from 'src/firebase/config'; import { doc, onSnapshot, DocumentSnapshot, DocumentData, } from 'firebase/firestore'; const getDocument = (collectionString: string, documentId: string) => { const error = ref<string | undefined>(); const document = ref<DocumentData | undefined>(); const docRef = doc(db, collectionString, documentId); const unsubscribe = onSnapshot( docRef, (doc: DocumentSnapshot<DocumentData>) => { if (doc.data()) { document.value = { ...doc.data(), id: doc.id, }; error.value = undefined; } else { error.value = "That document doesn't exist"; } }, (err) => { console.log(err.message); error.value = 'Could not fetch documents'; } ); // Cancel the listener when composable not in use watchEffect((onInvalidate) => { onInvalidate(() => { unsubscribe(); }); }); // Maybe use a "Watch" here to update the doucment and error refs? But I can't get it working. return { document, error }; }; export default getDocument; Ahora, al importar el componible getDocument , podría envolver todo en un reloj para asegurarme de que la referencia tenga un valor. Pero preferiría hacerlo dentro getDocument .
Por ejemplo:
src/composable/anotherComposable.ts
import getDocument from 'src/composables/getDocument'; const { document, error } = getDocument('users', 'USER_ID_HERE'); // I could wrap all my code here in a Watch, but I was hoping to avoid that. I want to use the Watch inside the getDocument composable to do the same thing. watch(document, () => { console.log(document.value); }); // This is how I would like to ultimately use the document ref after the Watch is moved inside the getDocument composable. Currently this will show as undefined. So I need to somehow put a Watch inside the getDocument composable to make this have a value. console.log(document.value);