Multiple executions of Google API sign in listener

I have been working on a Vue module that allows users to add events to Google Calendar easily. Once a user signs in, there is a listener in place to call a method for adding an event to the calendar. To access the gapi functionalities required for this task, I am utilizing a Vue library that can be found at https://github.com/cedpoilly/vue-gapi. However, I've encountered an issue where the addEvent method runs multiple times when trying to add another event after successfully adding one for the first time. This results in duplicate events being added. You can see the issue in action here: https://codesandbox.io/s/infallible-chaum-dg7nf

<template>
  <div class="row">
    <div class="col-md-6 ml-5 mt-3">
      <b-form>
        <b-form-group id="input-group-2" label="Add to" label-for="input-2">
          <b-button variant="outline-primary" @click="handleAuthClick">
            <b-icon icon="calendar3" aria-hidden="true"></b-icon> Google Calendar
          </b-button>
        </b-form-group>
      </b-form>
    </div>
 </div>
</template>
<script>
    export default {
     
      data(){
        return {
          show: true,
          disabled: false,
          items: '',
          event: '',
          gapi: null,
          partnerEmail: '',
          listner: null,
        }
      },
      methods: {
          onSubmit(evt) {
            evt.preventDefault();
            //alert(JSON.stringify(this.form));
            //this.meetingEdit(this.form);
            this.$router.push({ path: '/portal/meetingEdit/' })
          },
          deleteMeeting() {
            this.$router.push({ path: '/portal/meetingDelete/' })
          },
          addEvent() {

            var startDate = new Date(this.form.MeetingTime);
            var msDuration = (Number(this.form.Duration.split(':')[0]) * 60 * 60 + Number(this.form.Duration.split(':')[1]) * 60 + Number(this.form.Duration.split(':')[2])) * 1000;
            var endDate = new Date(startDate.getTime() + msDuration);
            var isoStartDate = new Date(startDate.getTime() - new Date().getTimezoneOffset() * 60 * 1000).toISOString().split(".")[0];
            var isoEndDate = new Date(endDate.getTime() - (new Date().getTimezoneOffset()) * 60 * 1000).toISOString().split(".")[0];
            var InviteesArr = [];
            var tempArr = this.form.Invitees.trim().split(',');
            for (var email of tempArr) {
              if (email !== "") {
                var obg = { 'email': email };
                InviteesArr.push(obg);
              }
            }

            var partner = { 'email': this.partnerEmail };
            InviteesArr.push(partner);

            this.event = {
              'summary': this.form.Topic,
              'location': this.form.InviteLink,
              'description': this.form.inviteDes,
              'start': {
                'dateTime': isoStartDate,
                'timeZone': this.form.Timezone
              },
              'end': {
                  'dateTime': isoEndDate,
                  'timeZone': this.form.Timezone
              },
              'attendees': InviteesArr,
              'conferenceData': null,
            };

            this.$getGapiClient().then((gapi) => {
              // gapi.sheets.spreadsheet.get(...)
              var request = gapi.client.calendar.events.insert({
                'calendarId': 'primary',
                'conferenceDataVersion': 1,
                'resource': this.event
              });

              request.execute( (event)=> {
                console.log(event);
                window.open(event.htmlLink, '_blank');
              });

              this.gapi.auth2.getAuthInstance().signOut();
              this.gapi = null;
            });
          },
          updateSigninStatus(bool) {
            if (bool) {
              console.log('login D');
              this.addEvent();
            } else {
              console.log('not login');
            }
          },
          handleAuthClick() {
            this.$getGapiClient().then((gapi) => {
              this.gapi = gapi;
              this.listner = this.gapi.auth2.getAuthInstance().isSignedIn.listen(this.updateSigninStatus);
              this.updateSigninStatus(this.gapi.auth2.getAuthInstance().isSignedIn.get());

              if (this.gapi.auth2.getAuthInstance().isSignedIn.get()) {
                this.addEvent();
              } else {
                this.gapi.auth2.getAuthInstance().signIn();
              }

            });
          }
        }
    }
    </script>

However, each click on the button triggers the addEvent() method multiple times.

Answer №1

When working with the function handleAuthClick(), be mindful of how you are calling updateSigninStatus which in turn calls addEvent(). It seems that within handleAuthClick(), there is another call to addEvent() causing redundancy.

To resolve this issue, make sure to only call addEvent() once within one of the functions.

UPDATE

The code snippet provided in the code sandbox differs from the code mentioned in your question due to the addition of the line:

recurrence: ["RRULE:FREQ=DAILY;COUNT=2"]
.

This indicates a recurrence setup for the event to repeat daily twice. If this is not intended, consider removing this line from your code.

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

The jQuery validation feature permits entering a code that falls within the range of user1 to user100

Here is an example where the user can only enter a code between 1 and 100. Otherwise, it will return false. var regexCode = /var regexEmail = /^0*(?:[1-9][0-9]?|100)$/; $(document).on('change','#code',function() ...

JavaScript Error Caused by Newline Characters

I'm facing an issue with extracting data from a textbox using JavaScript. What I'm attempting to do is retrieve the value from a textbox, display it in an alert, and then copy it. Here's the current code snippet: var copyString = "Date: < ...

Using AngularJS to add an element to an array based on a specified condition

dashboardCtrl Data app.controller('dashboardCtrl', ['$scope','$rootScope', function ($scope, $rootScope) { //Color $scope.Color = [{ colorname: "Red", number: "(3)" }, { colorname: "Brown ...

What is the most efficient method for designing this jQuery code to be reusable?

I am currently using dynamic Bootstrap popovers that are populated with content from my database. In PHP, it generates unique classes for each popover. My question is, when using jQuery, do I need to trigger the popovers individually? This is how I am cur ...

The system is facing difficulty in accessing the property 'user_first_name' as it is currently undefined

I'm having trouble registering a user with expressjs/mongoose as I keep receiving the error: TypeError: Cannot read property 'user_first_name' of undefined at C:\Quiz webPolitica\server.js:20:24 at Layer.handle [as handle_request] ...

What is the process for switching directories and renaming a file when uploading in nodeJs?

I am currently using multer and fs to handle the upload of an image file. How can I modify the directory where uploaded files are stored? Currently, all files are saved in my "routes" folder instead of the "uploads" folder created by multer. Additionally, ...

Clickable list element with a button on top

Within my web application, there is a list displaying options for the user. Each 'li' element within this list is clickable, allowing the user to navigate to their selected option. Additionally, every 'li' element contains two buttons - ...

Tips on integrating JavaScript with embedded Ruby code

I am attempting to generate a flash message that displays after a user clicks a link in my js.erb file. $('a').click(function(){ <% flash.now[:alert]= "Successfully added "%> this.innerHTML <% "to cart" %> }) M ...

What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects var obj1={ "name":"mayur", "age":23 } var obj2={ "name":"keyur", "age":29, "limit":54, "surname":"godhani" } //I am familiar with one approach var j1 = {name: 'Varun', age: 24}; var j2 = {code: &ap ...

Unable to access JQuery Draggable method within partial view

In my partial view, I have multiple Divs that are designed to be draggable using the JQuery UI draggable library. The JQuery scripts are included in the master page, and when I view the partial view on its own, everything works fine. However, when I load ...

The PHP script receives an empty string value passed from JavaScript

I am struggling to pass a string from my JavaScript code to my PHP code. Here is the code snippet that triggers when I hit Enter in a text input: $('#user').keypress(function(e) { if(e.which == 13) { var val = $(this).val(); ...

Implementing a DataTable filter functionality using external buttons or links

I want to enhance the search functionality of my table by incorporating a treeview style set of buttons or links next to it. This is how I envision it: Take a look at this design: https://i.sstatic.net/LAJXf.png Here's where it gets tricky. When I c ...

Creating a versatile JavaScript library that is compatible with various platforms such as browsers, NodeJS, and single page applications like React

My question is: Is it possible to convert a basic file into a versatile library that can be utilized with Browsers (via script tag), Node JS, and Single Page Applications using a single codebase? In the past, I have primarily used existing libraries witho ...

I am looking to retrieve a particular entry from a JSON data array and make some modifications to it

Initially, I fetched JSON data from the web server using the following code: $.getJSON(url,function(){ //my callback function; }); Now, I have received the data in the format shown below: {entries:[{title:'foo',id:'UUID',finished:nul ...

Why does 1&&2&&3 result in 3? Could someone clarify this for me?

During a recent interview, I was presented with this question about JavaScript evaluation order. My understanding is that in JavaScript, evaluation proceeds from left to right. So would 1 && 2 result in false? I came across another discussion where it w ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

Tips for eliminating duplicate values from an array

In my NodeJS code, I am currently comparing values in an array. The issue at hand is: I start with an empty array: var items = []; then proceed to insert some values into it: items[0] = {a:1, b:222}; items[1] = {a:1, b:333}; items[2] = {a:1, b:222}; ...

JavaScript: Understanding the concept of closure variables

I am currently working on an HTML/JavaScript program that involves running two counters. The issue I am facing is with the reset counter functionality. The 'initCounter' method initializes two counters with a given initial value. Pressing the &a ...

The v-tabs component in Vuetify seems to be unable to fill 100% of the available

When using the v-tabs component, I noticed that it doesn't take up 100% of the height. Upon further inspection, I found that all the tab items (tab contents) are wrapped inside a <div class='v-tab__items'> your content </div ...

The value attribute in the HTML input tag being dynamically increased by JavaScript

Hi there, can someone help me figure out how to save changes to the value attribute of an HTML input tag that is being incremented by JavaScript? Currently, every time I click on a specific element, the input field should increase by one. The problem is th ...