简体   繁体   中英

how to unsubscribe () a firebase collection in a vue.js component

In a vuejs component which dynamically retrieves data with firebase I would like to unsubscribe when I quit the component.

In the firebase documentation indicates that you must use the unsubscribe() function; to stop listening to the collection.

Unfortunately, this function cannot be used directly because it is declared undefined.

Here is the component code:

<script>
  import db from "../../firebase/init";

  let subscribe;
    
  export default {
  // ...
  
  beforeDestroy() {
    // Don't work form me !!!
    unsubscribe();
  },
  
  methods: {
     async getMyCollection() {
      try {
        subscribe = await db.collection("myCollection");
        subscribe.onSnapshot(snapshot => {
          snapshot.docChanges().forEach(change => {
            // Do something
            }
          });
        });
      } catch (error) {
        console.log(error);
      }

    }
  }
</script>

thanks for the help

Its because you have not defined the unsubscribe anywhere. Please check the code below.

<script>


import db from "../../firebase/init";

  let unsubscribe;
    
  export default {
  // ...
  
  beforeDestroy() {
    unsubscribe();
  },
  
  methods: {
     async getMyCollection() {
      try {
        unsubscribe = await db.collection("myCollection")
        .onSnapshot(snapshot => {
          snapshot.docChanges().forEach(change => {
            // Do something
            }
          });
        });
      } catch (error) {
        console.log(error);
      }

    }
  }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM