Navigating between Vue Router pages triggers multiple events within the mounted() lifecycle of VueJS

Currently, I am immersed in a project using Electron with a Vue CLI setup and the Vue CLI Plugin Electron Builder. The overall functionality is working perfectly fine except for a peculiar bug that has recently surfaced.

The issue arises when navigating between pages using the Vue Router - the event listener in the component's `mounted()` property gets triggered twice, resulting in an 'N+1' problem.

To elaborate on this predicament, within my project, I have two components named `Home.vue` and `HelloWorld.vue`. In `Home.vue`, upon clicking a button, I trigger an event to the main process and listen for the corresponding event reply using the `mounted()` property of the same component. Initially, everything functions as expected.

However, upon switching to the `HelloWorld` page and then returning to the `Home` page, every click of the button not only sends one event but receives two event replies from the main process. This behavior exacerbates when switching back and forth between pages, revealing a pattern resembling the 'N+1' issue.

In order to illustrate the problem more clearly, I have created a GIF showcasing the issue:

Home.vue

<template>
  <div class="home">
    <button @click="send()">Home</button>
  </div>
</template>

// Script section

export default {
  name: "Home",
  data() {
    return {
      cause: null
    }
  },
  mounted() {
    window.ipcRenderer.on("home:reply", event => console.log(event));
  },
  methods: {
    send() {
      window.ipcRenderer.send("home");
    }
  },
};
</script>

main.js

ipcMain.on("home", event => {
  return event.reply("home:reply");
});

My Vue Router configuration is based on the default structure provided by Vue CLI. As evident from the code snippet above, I simply trigger an event upon button click and await the respective event reply using the `mounted()` property within the same component.

I did come across a similar discussion on Stack Overflow here, but unfortunately, I haven't been able to resolve the issue myself. At this point, I'm baffled as to what might be causing this discrepancy in my code 🥱

Answer â„–1

It's important to remember to unregister the event handler when the component is destroyed. If you forget, you'll end up re-registering the same event handler every time the component is mounted, leading to potential issues.

mounted() {
  window.ipcRenderer.on('app:reply', this.handleAppReply)
},

destroyed() {
  window.ipcRenderer.off('app:reply', this.handleAppReply)
},

methods: {
  handleAppReply(event) {
    console.log(event)
  }
}

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

Passing along a request using Node.js

I am facing an issue in my project where I need to redirect requests received by a nodejs endpoint to a .NET 7 web API endpoint. The nodejs endpoint is triggered by an external party and it receives the request as expected. However, there seems to be a pro ...

What is the best way to fix the "Module not detected: Unable to locate [css file] in [directory]" error when deploying a Next.js website on Netlify?

Trying to deploy my site on Netlify from this GitHub repository: https://github.com/Koda-Pig/joshkoter.com, but encountering an error: 10:02:31 AM: Module not found: Can't resolve '../styles/home.module.css' in '/opt/build/repo/pages&ap ...

What is the best method for incorporating meta data, titles, and other information at dynamic pages using Node.js and Express?

I am currently exploring methods to efficiently pass data to the html head of my project. I require a custom title, meta description, and other elements for each page within my website. Upon initial thought, one method that comes to mind is passing the da ...

The issue of ERR_MODULE_NOT_FOUND in Node.js express.Router arises when attempting to import new routes

Something strange is happening. I was in the process of organizing my routes by creating a new folder. Within this folder, I used the express.Router API to define the routes and then exported the router itself. Here is an example code snippet from my pos ...

Access your Vue.js application using Google Sign-In (GIS)

Having trouble with the discontinuation of gapi.oauth2 by Google and finding the new Sign in With Google tools confusing. Project Structure Looking to implement user sign-in with Google on my Vue frontend and authenticate them using OIDC server flow on ...

Using VueJS for reactive binding效果

I am attempting to assign a class using the following syntax: :class="{active: favs.medium_title.fontWeight === 'bold'}" However, the fontWeight attribute is not yet defined when the component loads. This is an excerpt from my object: favs: { ...

How can I transform the overall value into a percentage in Vue.js or JavaScript?

Is there a way to create a progress bar in VueJS 3 with Nuxt Js by converting the total value to a percentage and displaying it as a style width value? For example, if 40% out of 100% equals 400USD out of 1000USD, can we achieve this using a function in an ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

Issue with preventdefault() function in Internet Explorer 8

I've encountered a problem while working on a page that heavily utilizes ajax. Everything seems to be functioning well across different browsers, except for one final step that is broken in IE8 and below. You can view the issue on this demo page: To ...

The dynamic change of a required field property does not occur

I am facing an issue where one of my fields in the form should be mandatory or not based on a boolean variable. Even if the variable changes, the field always remains required. I'm puzzled about why my expressionProperties templateOptions.required is ...

Construct a div element using JSON information

I am retrieving information from a database and organizing it into a JSON array. Here is the data that I have: [{"id":"0","name":"red","percentage":"60"},{"id":"1","name":"blue","percentage":"58"},{"id":"4","name":"green","percentage":"12"}] The structu ...

Express Node fails to launch

I recently decided to try my hand at Express and learn more about it. However, I encountered an issue while trying to start a server. Initially, I attempted to access 127.0.0.1:8080 through Express but nothing seemed to be happening. Although I copied most ...

Can the grunt command be executed automatically after saving code in TypeScript?

As a newcomer to FrontEnd and JavaScript coding in TypeScript, I find myself constantly needing to follow these steps after making a code change: save the code -> compile it using Grunt -> reload the webpage. It can be quite time-consuming. Is there a way ...

HTML tends to disregard the dimensions specified in the JavaScript file

I'm currently working on replicating an Etch-a-Sketch style drawing board where hovering over a single pixel with the mouse changes its color. However, I've hit a roadblock when it comes to drawing the board. The flexbox container doesn't se ...

What sets @vue/cli-plugin-unit-jest apart from vue-jest?

Can you explain the distinction between these two software bundles? @angular/cli-plugin-unit-jasmine angular-jasmin If I already have one, is there a need for the other? And in what circumstances should each be utilized? ...

Creating responsive modal windows in Vue and Laravel to dynamically adjust to the screen size

I am currently working with a modal window code snippet. <transition name="modal" @close="showModal = false"> <div class="modal-mask" style=" width: 90% !important;"> <div class="modal-wrapper"> < ...

Calculating JS functions before images are loaded

Following up on a previous question, I am utilizing JavaScript code from another article to position a "content" div relative to a fixed div in my project. However, the issue arises when the positioning of the "content" div is calculated only after all the ...

Is it possible to integrate two calendars into the `DatePicker` component of MUI?

The <DateRangePicker/> component from MUI has a prop called calendars which determines the number of calendars displayed inside the component popup. Here is an example: If the calendars prop has a value of "3", it will look like this: https://i.sta ...

Eliminate the ArrayOfObjects by filtering out the items with a specific ID

Here is an array of objects I've named mycart[]: [{"id":"6","quantity":"20","price":1500,"title":"casual blue strip"}, {"id":"10","quantity":"2","price":1500,"title":"casual blue round neck"},{"id":"5","quantity":20,"price":150,"title":"casual ...