What is the proper way to invoke a method within the same class, Class A?

I'm facing an issue where I need to call the method getData() inside my AJAX function again if a 401 status occurs and the counter is less than or equal to 1. However, for some reason, the method is not being called in that particular scenario. How can I go about calling that method from within the same class?

export default class Search {
    constructor(){
        this.result = {};
    }

      getData(callback, url){
        var counter = 0;
        alert("GET DATA CALLED " + counter);
        $.ajax({
            'url': proxy + url,
            'type': 'GET',
            'content-Type': 'x-www-form-urlencoded',
            'dataType': 'json',
            'headers': {
              'Authorization': 'bearer ' + localStorage.access_token
            },
            'success': function (result) {
              documentView.fillDocuments(result);
              callback(result);
            },  
            'error': function (XMLHttpRequest, textStatus, errorThrown) {
          //    alert('Error: ' + errorThrown);
              console.log(XMLHttpRequest.status + ' ' + 
                  XMLHttpRequest.statusText);
              return "";
            }, statusCode: {
              401: function (response) {
                counter++;
                alert("401");
                if(counter <= 1){
                  refreshToken(); // CALLED
                  getData(callback, url); // NOT CALLED
                } 
              }
            }
        });
      }

Answer №1

Your implementation of standard function expressions is generating a new context for 'this', this can be avoided by utilizing arrow functions.

Here's an example snippet to demonstrate the concept.

export default class Search {
    constructor() {
        this.result = {};
    }

    getData = (callback, url) => {
        var counter = 0;
        alert("GET DATA CALLED " + counter);
        $.ajax({
            url: proxy + url,
            type: "GET",
            "content-Type": "x-www-form-urlencoded",
            dataType: "json",
            headers: {
                Authorization: "bearer " + localStorage.access_token
            },
            success: (result) => {
                documentView.fillDocuments(result);
                callback(result);
            },
            error: (XMLHttpRequest, textStatus, errorThrown) => {
                //    alert('Error: ' + errorThrown);
                console.log(
                    XMLHttpRequest.status + " " + XMLHttpRequest.statusText
                );
                return "";
            },
            statusCode: {
                401: (response) => {
                    counter++;
                    alert("401");
                    if (counter <= 1) {
                        refreshToken(); // EXECUTED
                        this.getData(callback, url); // NOT EXECUTED - Should now execute.
                    }
                }
            }
        });
    }
}

Answer №2

Call this.getData(callback, url) - to invoke the method within the class.

Make sure to update all function declarations function () {} with arrow functions () => {} inside the getData() function.

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

Cannot reset Ajax field in Yii framework

Within my form, there is a specific field that gets populated through an Ajax call. However, I've noticed that when I use the code: <?php echo CHtml::resetButton('Reset');?> it successfully resets all fields in the form except for t ...

Tips for implementing a page loading spinner within my HTML content with jQuery Mobile or jQuery

Looking for a way to display a page loading spinner within the content of an HTML page using jQuery mobile or jQuery. I've attempted some coding with jQuery and AJAX, but it's not functioning correctly. Any suggestions or solutions would be great ...

Utilizing React JS and Express to efficiently filter AJAX responses

I am currently developing a MERN (Mongo, Express, React, Node) application. My approach involves using Ajax to extract data from the MongoDB. My next goal is to refine the response by implementing a query in the GET request. Unfortunately, I seem to have ...

The server seems to be having trouble with Ajax Cascading DropDownLists that use a web service - the lists are showing up empty and not

Seeking assistance with ajax cascading dropdown lists that function perfectly on my local machine. However, upon deployment to the server, all dropdown lists appear empty without any error messages. Is there anyone who can lend a hand? My code snippet: ...

The appearance of responsive CSS is altered when deployed compared to when it is viewed on the

I'm a beginner in web development and facing an issue with my mobile CSS. The strange thing is that when I view it on localhost, everything looks great, but once deployed (tried both Heroku and GitHub), it appears distorted. Even when I make extreme c ...

Issue with rendering second series in Highcharts Master Detail Chart

I'm currently facing an issue while setting up a Master Detail chart. Initially, both the master and detail graphs display line series and errorbar series. However, upon selecting a new range on the master chart, only the Line appears in the detail ch ...

Encrypting href links in Nodemailer with Handlebars for forwarding purposes

I am working on a project that involves utilizing NodeMailer + Handlebars for sending and tracking emails. I am interested in changing every href link to the project URL before redirecting to the destination link. For example: Original email: <a href ...

What method can we use to verify if an object falls within a specified date range when filtering?

Looking to determine if the current filter object falls within a specific date range and return a boolean value based on that condition. However, the code provided always returns the data. Can anyone spot the error in the implementation or suggest a better ...

Unlock the full potential of custom authorization providers when integrating them with Supabse

Supabase user here looking to implement authorization with a third-party service that isn't on the supported list. Any suggestions on how to go about this? ...

Choose a list in order to create a new list

If I were to choose a specific state in Nigeria, what steps should I follow to generate a drop-down menu with a list of local governments within that state? ...

Looking to enhance code readability using regular expressions

While I am not a programmer, I enjoy exploring and learning new things. Here is what I have: 1) My URL is structured like this: http://site.com/#!/show/me/stuff/1-12/ 2) I have a jQuery pagination script that displays the number of available pages. Each ...

Struggling to access properties of a javascript object while trying to slice it within table pagination

As I work on this program, my goal is to apply a function to an Array of objects to display rows with information from this group of users. However, TypeScript is throwing various errors when I try to access this information. I'm unsure of what I&apos ...

Verification response parameter not received from Google Authentication Express

I've been working on implementing a "sign in with Google" feature for my localhost website. Despite receiving the POST request, I noticed that it lacks the credential parameter. I'm unsure if this issue lies within the code or the API configurati ...

Capable of generating a string-keyed map that results in an "Unexpected number error" when the key is referenced

Take a look at the following code snippet: var arr = [{"id":"123", "name":"Jyotirmoy"}]; var mapObj = {}; for(var i=0; i < arr.length; i++){mapObj[arr[i].id] = arr[i];} After creating the map, attempting to access it using the key 'mapObj.123&ap ...

The appropriate method for transferring a prototype to an object

From my perspective, prototypes work like this: let Animal = function() { this.bark = "woof"; } Animal.prototype.barkLoud = function() { return this.bark.toUpperCase(); } let x = new Animal(); x.barkLoud() = "WOOF"; I f ...

Retrieving previous data following an AJAX request using the GET method in Laravel 5.5

I have encountered an issue while using two ajax calls on a single page. On one side, I am making an ajax post request to store data and submit color in a database called "color_store." On the other side, I am trying to retrieve all the colors from that ta ...

Update the chosen option in a dropdown list with jQuery and javascript

I need to set the value of a column in a repeater so that once it's assigned, the column will display the current selection from the dropdown. I have the correct value to assign in $('#myname_' + rowIndex).text(), but when I try to assign t ...

What steps are involved in setting up role-based authentication using Node.js?

Essentially, I am looking for a way for nodeJS to determine if the user logging in through the login page is an admin or not. If they are an admin, they should be directed to the admin page; if not, they should be sent to a different page. Currently, I ha ...

Initialize React Native project

Which ruby command shows the path to Ruby: /Users/User/.rbenv/shims/ruby Ruby -v command displays the version of Ruby installed: ruby 2.7.5p203 (2021-11-24 revision f69aeb8314) [x86_64-darwin21] Which bundle command reveals the path to Bundler: /Users/Us ...

Is there a Ruby gem similar to Readability that anyone can recommend?

Readability is a nifty JavaScript tool that magically transforms a cluttered HTML page into a more user-friendly format. I'm on the hunt for a Ruby implementation or something along those lines - does anyone know of a library that offers similar funct ...