What is the best way to remove a Firestore listener from my Vuex action?

Currently, I'm utilizing Firestore to retrieve the stored data in my vuex store. One aspect that is puzzling me is how to properly detach the listener when, for instance, a user signs out.

fetchExercises ({commit, getters}) {
  const db = firebase.firestore()
  const exercises = db.collection('exercises').where('userId', '==', getters.user.uid)

  // Real time feed retrieval
  exercises.onSnapshot(querySnapshot => {
    commit('setLoading', true)
    let source = querySnapshot.metadata.hasPendingWrites ? 'Local' : 'Server'

    console.log(`Source ${source}`)
    if (querySnapshot) {
      querySnapshot.forEach(doc => {
        commit('watchExercises', {
          title: doc.data().title,
          language: doc.data().language,
          translated: doc.data().translated,
          lastOpen: doc.data().lastOpen,
          dueDate: doc.data().dueDate,
          uid: doc.data().uid,
          userId: doc.data().userId,
          words: doc.data().words,
          shared: false
        })
        const exercise = {
          title: doc.data().title,
          uid: doc.data().uid,
          lastOpen: doc.data().lastOpen,
          language: doc.data().language,
          translated: doc.data().translated,
          dueDate: doc.data().dueDate,
          words: doc.data().words,
          shared: false
        }
        commit('updateExercises', exercise)
      })
    }
    if (querySnapshot.size === getters.loadedExercises.length) {
      commit('setLoading', false)
    }
  })
}

The above action handles data fetching. My current dilemma revolves around how to detach the listener within another action, such as signing out.

Answer №1

this.unsubscribe = this.exercises.onSnapshot(
    // place your code here
);

// Use this function to stop monitoring changes
// Recommend using it when a user signs out, for instance

this.unsubscribe();

Learn More Here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty sending emails with Nodemailer

This is a simple example showcasing the usage of Nodemailer library. var http = require('http'); var port = process.env.PORT || 8080; var async = require('async'); var nodemailer = require('nodemailer'); // Creating a transp ...

What could possibly be causing a syntax error in my JavaScript code?

<script type="text/javascript> $(document).ready(function(){ $("a.grouped_elements").fancybox( 'transitionIn' : 'elastic', 'transitionOut' : 'elastic', 'speedIn' : 600, ...

Error Message: The function "menu" is not a valid function

I've encountered an issue with a function not being called properly. The error message states "TypeError: menu is not a function." I attempted to troubleshoot by moving the function before the HTML that calls it, but unfortunately, this did not resolv ...

Is there a way to redirect the user directly to the upload page without displaying the response?

Recently, I came across this code snippet that adds a progress bar to an upload form. Currently, the code displays the response from the upload page below the form. However, my goal is to redirect the user to the upload page so they can view the response t ...

What is the method for configuring Express to serve static files from a parent directory?

If I have a nodejs express application with the following folder structure: -app - frontend - assets - images - scripts - styles - ... - pages - backend - server.js How can I serve the static files in the assets fold ...

Storing form information within the view

What is the best way to transfer data between views in AngularJS? I tried using $rootScope but it's not working as expected. ...

The error message states, "undefined cannot be used as a function."

For testing purposes, I am running checks on my Service using httpBackend. Specifically, I am focusing on a simple get request that needs to be tested for the response code. However, despite my efforts, I keep encountering this error: TypeError: undefined ...

Creating a user-friendly error message on the interface using JavaScript

I have implemented a table that showcases data from the Geonames API. Currently, I am working on creating a function to handle errors when the user forgets to fill in the input fields and then trigger an alert on the interface. The code snippet below sho ...

What is the best way to update a tag element in Vue.js?

Currently, I am working with Vuejs and struggling with a specific task - How can I replace the div tags with button tags? In the DOM, <div class="prev">prev</div> <div class="next">next</div> I would like to ac ...

What could be causing my dropdown menu to not appear when clicked?

I am trying to implement the functionality shown in the image. When the Settings button is clicked, a window should open allowing the user to navigate to their desired option. However, I am facing an issue where nothing happens when the button is clicked. ...

Ways to delete scheduled tasks in BreeJS

I am currently working on an express server that initiates a recurring job upon client request for a specific duration. The challenge I am encountering is figuring out how to stop and remove that particular job once it has been completed. The following is ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

Date Range Selection Widget malfunctioning when used within a popup modal

Having trouble with integrating the rsuite daterangepicker and antd's daterangepicker into a React Material UI Dialog/Modal. The date picker popup seems to either not show up or appear outside of the modal window. Take a look at the image below: Clic ...

Next.js rewrites are functioning properly, however, there seems to be an issue with locating the Javascript

I am currently in the process of setting up multiple Vercel/Next.js projects under one domain, as recommended in this helpful guide. Given that each of my apps have unique requirements, it makes sense for me to separate them into their own projects. The ...

How to utilize a defined Bootstrap Modal variable within a Vue 3 single file component

I'm diving into the world of TypeScript and Vue 3 JS. I created a single-file-component and now I'm trying to implement a Bootstrap 5 modal. However, my VSCode is showing an error related to the declared variable type. The error message reads: ...

Unable to invoke function on HTML element

Recently, I've ventured into writing jQuery-like functions in Vanilla JS. While my selectors seem to be working fine, I encounter an "is not a function" error when trying to call the append function on an HTML element. var $ = function(){ this.se ...

Unlocking Discord Account Information through OAuth2

Currently, I am in the process of developing a moderation bot for Discord. I am working on implementing a paid plan and as part of that, I require users to log in with their Discord account using OAuth2. This allows me to retrieve user data and identify wh ...

Creating a Javascript countdown timer that does not involve displaying the

I stumbled upon this code on a website, but there's one tweak I'd like to make. Unfortunately, I can't seem to figure it out myself, so I'm reaching out for some help. What I want to achieve is removing the year from the date so that th ...

Having trouble downloading a PDF file on a local server with React and the anchor tag element

Having trouble downloading a pdf file from my react app to my Desktop. I've reached out for help with the details How to download pdf file with React. Received an answer, but still struggling to implement it. If anyone new could provide insight, that ...

Creating a dynamic progress bar animation that transitions smoothly from one color to another using jQuery

Is there a way to change the barColor so that it has different colors at the start and end? var EasyPieChart = function(el, opts) { var defaultOptions = { barColor: '#FFEA82', trackColor: '#e1e1e3', scaleCol ...