Improving a Vue.js notification component with data retrieved from a fetch request result

Struggling with updating the content inside a vuetify v-alert.

There's an issue when trying to update Vue component properties within the sessionID.then() block after logging into a system and receiving a session id.

Vue.component('query-status', {
  template: `
    <div>
      <v-alert :type="type">
        {{ alertText }}
      </v-alert>
    </div>`,
  data() {
    return {
      alertText: '',
      type: 'success'
    }
  },
  methods: {
    checkQueryStatus: function() {
      var sessionID = login();
      sessionID.then(function(result) {
        this.alertText = result;
      });
    }
  }
});

The question remains, why doesn't the sessionID.then block have access to the alertText property?

Answer №1

If you fail to bind the this pointer, the inner function will not be able to access it.

To resolve this issue, you have a few options:

checkQueryStatus : function() {              
  var sessionID = login();
  var that = this;
  sessionID.then(function(result) {
    that.alertText = result;
  });
}

You can also consider using an ES6 arrow function:

checkQueryStatus : function() {              
  var sessionID = login();  
  sessionID.then(result => {
    this.alertText = result;
  });
}

Alternatively, you can bind the this pointer using Function.prototype.bind:

checkQueryStatus : function() {              
  var sessionID = login();  
  sessionID.then(function(result) {
    this.alertText = result;
  }.bind(this));
}

Another approach would be to utilize async / await:

methods: {
  async checkQueryStatus() {              
    this.alertText = await login();
  }
}

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

What is the correct way to dynamically switch between RTL and LTR in React with Material UI?

I recently learned that in order to support right-to-left (RTL) languages with Material UI, you need to follow these steps. I have a select input that allows users to switch between languages, changing the overall direction of the app. The core of my appl ...

Using javascript to extract values from nested JSON structures without prior key knowledge

My JSON data is structured as follows: {"sensors": {"-KqYN_VeXCh8CZQFRusI": {"bathroom_temp": 16, "date": "02/08/2017", "fridge_level": 8, "kitchen_temp": 18, "living_temp": 17, ...

I am having trouble getting ng-change to work. Can someone explain how to properly implement ng

I am facing an issue where the ng-change function is not working for obtaining the team_id and team name. Can someone suggest a more efficient solution to resolve this problem? <th style="width:20%"> <select style="height: 40px; fon ...

Save the raw InputMask data in Formik with Material-UI

I currently have Input Mask implemented with a customized Material UI text field inside a Formik form: <InputMask mask="999-99-9999" maskChar="X" value={values.ssn} ...

Ramda represents a distinct alternative to traditional vanilla JavaScript

I'm feeling a bit confused about how Ramda really works. I found this code and I'm not entirely sure how it functions. const render = curry( (renderer, value) => is(Function, renderer) && renderer(value) ); I just need to grasp an ...

What is the best way to set up webpack to exclude a non-existent asset in my scss files?

I am encountering an issue while compiling my scss file. Within the .scss file, I have the following code: body { background-image: url("/static/background.webp"); } The error message I'm seeing is as follows: error in . ...

How can I trigger a PHP function by clicking a button on a PHP page that has already been loaded?

While I've come across a variety of examples, I haven't been able to make them work for the simple task I need to accomplish. The code in these examples seems overly complex compared to what I require. In essence, I have a form that processes dat ...

Apply a see-through overlay onto the YouTube player and prevent the use of the right-click function

.wrapper-noaction { position: absolute; margin-top: -558px; width: 100%; height: 100%; border: 1px solid red; } .video-stat { width: 94%; margin: 0 auto; } .player-control { background: rgba(0, 0, 0, 0.8); border: 1px ...

Invalid file name detected during the download process

Below is the Javascript code I currently use to download a pdf: var link = document.createElement('a'); link.innerHTML = 'Download PDF file'; link.download = "Report.pdf"; link.href = 'data:application/octet-stream;base64 ...

Issues with Angular preventing app from launching successfully

So I've been working on a Cordova app with AngularJS and everything seems to be running smoothly in Chrome and other browsers. However, when I try to install the apk on Android, AngularJS doesn't seem to execute the index.html upon launch. What& ...

Hide elements forever once the form is submitted

I'm seeking help to figure out how to make certain elements disappear after a form submission on my website's dashboard page. Specifically, I need to hide three elements once the user has submitted a form. Elements that need to be hidden: .vc_t ...

Unable to access $_SESSION variable when making AJAX request from a different port

After creating a website with PHP on port 80 (index.php) and setting the session variable with the userid upon login, I encountered an issue when clicking on a link that redirected me to port 8080, which is where a JavaScript file containing node.js proces ...

Converting function arguments into key/value pairs: A simple guide

I am looking for a way to achieve the following in NodeJS: a = 10 b = 20 c = 30 d = 40 ...... ...... function createObject(a, b, c, d, ....) => { // This function is expected to return an object. // return { a : 10, b : 20 ...

What is the process for retrieving matched information from a drop-down menu in HTML?

Is there a way to retrieve data from angularjs like this: This is the list of data I need to access: $scope.orderStatus = [ { os: 'Open', value: 1 }, { os: 'Completed', value: 2 }, { os:'Cancelled',value: 3 }, ...

Awaiting fulfillment - Promise remains pending as loop executes queries

I have a scenario where I receive an array containing multiple data elements and need to perform a query for each element in the array. However, this is resulting in a promise pending response. How can I resolve this issue? What could be causing it? getFa ...

What is the process of creating a download link for a server file in a web browser?

I am attempting to create a straightforward download link for a PDF file that users can upload and then have the option to download. I would like this download feature to appear either in a pop-up box or simply on the Chrome download bar. Despite trying v ...

What steps can be taken to remove the search parameter responsible for the error?

Imagine having a webpage that displays search results based on the parameters in the URL, like this: https://www.someurl.com/categories/somecategory?brands=brand1,brand2,brand3 This URL will show listings for only brand1, brand2, and brand3. Additionally ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

Generating an order prior to payment being made by the customer

When a user selects a product and clicks the pay button, they are redirected to Stripe where a new order is created. However, if the user changes their mind and cancels the payment during the Stripe checkout process, the order has already been created. How ...

Wordpress team exhibition

Does anyone know how to create a Team showcase slider in Wordpress? I have been using slick slider, but I'm looking for a way to add team members easily through a plugin rather than manually. I found an image of what I want it to look like. Can any ...