When attempting to access VueJS `this.progress` inside a window function, it

Currently, I am implementing a Facebook login feature on my website and displaying a loading progress indicator for the user until I receive authentication response from Facebook. However, I encountered an issue with hiding the progress bar as the variable to control it is undefined within the window function.

In my code snippet:

initFacebook() {
    this.progress=true;
      window.fbAsyncInit = function() {
        window.FB.init({
          appId: "MY-APP-ID", //You will need to change this
          cookie: true, // This is important, it's not enabled by default
          version: "v2.6",
          status: false,
        });
        
        window.FB.login(function(response) {
          
        if (response.status === 'connected'){

        window.FB.api('/me?fields=id,name,email', function(response) {
        console.log( response); 
    })
     
        } else {
          console.log("User cancelled login or did not fully authorize.");        

        }

      },
      
      {scope: 'public_profile,email'}
      );
    this.progress = false;
console.warn(this.progress);

      };

    },

I am facing difficulty setting this.progress to false once all responses are received from Facebook and encounter an error while trying to access this variable using console.log.

The error message states:

Login.vue?7463:175 undefined

I would appreciate any advice on how to properly set the this.progress variable to false once the authentication process is completed successfully.

Answer №1

It's worth trying to convert all function() calls into arrow function calls, like this: () =>

The issue arises when using a function() because it can break the global Vue scope. In this case, vue's this is not accessible within a function() call, but it can be accessed within an arrow function () => {}

When in a block scope (function() { syntax), "this" is bound to the nested scope instead of Vue's instance. If you want to maintain Vue's "this" inside a function, consider using an arrow function (ES6) or defining a constant like const that = this and utilizing "that" in a regular function().

To see if it makes a difference, try converting the code to use arrow functions:

initFacebook() {
  this.progress=true
    window.fbAsyncInit = () => {      
      window.FB.init({
        appId: "MY-APP-ID", //Make sure to customize this
        cookie: true, 
        version: "v2.6",
        status: false,
      });

      window.FB.login((response) => {            
        if (response.status === 'connected'){
          window.FB.api('/me?fields=id,name,email', (response) => {
            console.log( response)
          })     
        } else {
          console.log("User cancelled login or did not fully authorize.")
        }
      },      
    {scope: 'public_profile,email'});
    this.progress = false
    console.warn(this.progress)
  };
},

This solution worked for me too! I encountered the same issue - check out more details here: Nuxt plugin cannot access Vue's 'this' instance in function blocks

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

Using Double Quotes in v-b-tooltip in Vue Bootstrap

I recently implemented the vue bootstrap tooltip feature on my website. You can find more information about it here. Currently, I have a tooltip set up like this: <label>Encoding <feather-icon icon="AlertCircleIcon" class=" ...

Thymeleaf not triggering JQuery click event

Currently working on a Spring Boot site where I have a list of elements, each containing a link. The goal is to trigger a javascript function when these links are clicked. <div class="col-sm-4" th:each="product : ${productsList}"> <!-- Code... ...

Addressing React Native Rendering Problems

I'm currently working on a weather application and facing some challenges with rendering the forecast. I'm uncertain whether it's related to the styling. I've tested the API call through the browser and encountered no errors in Android ...

The initial dropdown menu in PHP coupled with Javascript fails to retain my chosen option

As a novice PHP programmer, I successfully created a double drop-down list from a MySQL database. The idea is to choose a claims hub in the first box and then select an attorney associated with that specific hub in the second box. However, I am facing an ...

Muting the unused variable alert in JavaScript

Whenever I run my typescript compiler, it always gives me errors about unused variables. In C programming, I would prevent this using the following method: void foo(int bar) { (void)bar; } Is there a similar workaround in JavaScript? ...

What could be the reason for the tooltip failing to initialize?

Below is the code snippet I've written : $(containerObj).find('a').tooltip ({ selector : "[data-toggle=tooltip]", title : 'sTooltip', placement : 'auto', container : 'body', trigger : 'hov ...

Importing an array of Vue components to be exported and utilized in the app.js file

I'm currently working on a Laravel 8 project with vue.js v2.6 and I want to clean up my app.js file by moving all of my Vue.component() declarations to a separate file. To achieve this, I created js/vueComponents.js where I placed all the vue componen ...

Dividing large pages into smaller components

In the realm of code styles, I am faced with a question specific to Vue.js as that is the framework I am utilizing for my front end development. As I dive into building a complex web application with Vue.js, even with the use of single file components, I ...

Tips for making sure AngularJS runs a function and its subfunction sequentially

How do I run the code below to display the details of each flavor and its corresponding ITEM ID in a specific order. Execution Format: Flavor1, Flavor2 -- Getflavors() Flavor1 ITEM1, ITEM2... -- GetItemIDs_ofeachFlavor(MapFlvID) GET ITEM1 DETAILS and ad ...

Converting a Javascript string to 'Title Case' does not yield any results

I'm having trouble identifying the bug in this code as it's not generating any output: function convertToTitleCase (inputString) { var wordArray = inputString.split(' '); var outputArray = []; for (var j = 0; j ...

Creating a Custom Error Object in Feathersjs: A Step-by-Step Guide

If I were to throw a GeneralError when calling a service, how can I create an error object with the following structure: { "status": "Failed", "code": "500_1", "detail": "Something is wrong with your API" } I have attempted to add this in the error hook: ...

Bizarre error when injecting Factory into Controller in AngularJS

After scouring through countless posts on various forums, I have yet to find a solution to my unique problem. I find myself in a peculiar situation where I am trying to inject a Factory into a Controller, and despite everything appearing to be in order, i ...

show image with the help of jquery and ajax

To showcase company information along with an image, I have a controller set up as follows: public JsonResult DisplayCompanyDetails() { CompanyModel cm = new CompanyModel(); string query = "select CompanyName,Address,Conta ...

Limiting jQuery datepicker to only show the selected date and disabling all others

I have two datepickers named startdate and enddate. My goal is to restrict all other dates in the enddate datepicker except the selected date from the startdate datepicker. For instance, if I choose 15/12/2016 from the startdate datepicker, I only want the ...

Passing an array of ID's between two components in Angular: A comprehensive guide

Greetings fellow readers, I have encountered a new challenge in my Angular project. I need to pass an array of IDs from one component to a completely unrelated component. Most solutions suggest using ViewChild, Input, or Output, but since the components ar ...

How can we redirect to the current page in JavaScript while passing an additional variable?

How can I capture the current URL and add "&p=1" to it before redirecting? Looking for a solution! ...

Choosing items in select2 ahead of time using JSON

Is there a way to preselect an option in select2 when using disabled: true and locked: true options? I am retrieving JSON data for a text field and would like to have an option preselected. Does something like this exist? { id: 0, text: 'story' ...

Error encountered while updating in the midst of an ongoing state transition, e.g. within the `render` method

class MyComponent extends React.PureComponent { constructor(props) { super(props); this.state = { obj: [], externalObj: [], }; } fetchData = (external) => { ... arr = arr.filter(a => a.toLowerCase().includes(&ap ...

How can Vuejs be utilized to showcase data with the onChange event?

I'm working on a Vuejs component and I currently have this code snippet: <div class="col-sm-9"> <Select class="form-control" name="building" v-model="allBuild.id" @change="showBuilding($event)& ...

The hyperlink to a different webpage does not trigger any JavaScript functionalities or render any CSS styles

I am facing an issue with linking HTML pages that run Javascript and JQuery Mobile from another HTML page. My link setup is as follows: <a href="hours.html">Hours</a> The linking page and the linked pages are in the same directory. However, ...