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

473
Views
Firebase y Nuxt3: ¿Cómo separar el oyente onSnapshot?

Estoy usando Firestore onSnapshot listener en un componente de mi aplicación Nuxt3. Me pregunto cómo separar el oyente cuando el componente está desmontado. ¿Cómo separo con éxito el oyente? Supongo que podría llamar al oyente para cancelar la unsubscribe en el onUnMounted .

Configuré el oyente en un onMounted() y separado de esta manera:

 <script setup> import { useUserStore } from '@/stores/user' import { onSnapshot, collection, query, where, getDocs } from 'firebase/firestore' const userStore = useUserStore() const loading = ref(false) const userPosts = reactive([]) const unsubscribe = ref(null) onMounted(async () => { const { firestore } = useFirebase() const userPostsRef = collection(firestore, 'posts') const q = query(userPostsRef, where('uid', '==', userStore.userProfile.uid)) unsubscribe.value = onSnapshot(q, (snapshot) => { snapshot.docChanges().forEach((change) => { if (change.type === 'added') { console.log('added', change.doc.data()) userPosts.push(change.doc.data()) } if (change.type === 'modified') { console.log('modified', change.doc.data()) userPosts.splice( userPosts.findIndex((post) => post.id === change.doc.id), 1, change.doc.data() ) } if (change.type === 'removed') { console.log('removed', change.doc.data()) userPosts.splice( userPosts.findIndex((post) => post.id === change.doc.id), 1 ) } }) }) loading.value = false }) onUnmounted(() => { unsubscribe.value //<-----is this the correct way to detach it? })

Editar: acabo de confirmar que el método anterior no elimina el oyente porque cada vez que navego fuera de la página, obtengo los registros de la consola de ('agregado', 'modificado', etc.). SO, debo estar haciendo algo mal.

about 4 years ago · Santiago Gelvez
1 answers
Answer question

0

La cancelación de unsubscribe es una función, por lo que deberá llamarla como se muestra a continuación:

 onUnmounted(() => { // call only when unsubscribe is not null unsubscribe.value && unsubscribe.value() // or use optional chaining unsubscribe.value?.(); })
about 4 years ago · Santiago Gelvez 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!