Scope Function Challenges in Vue.js Method

Having a SetInterval embedded within a Promise in Axios is causing an error when trying to run a function inside the SetInterval block. The specific error encountered is:

    methods: {
    getJson() {
        axios.post(url, FormObject, config)
        .then(response => {
        var searchId = JSON.stringify(response.data.searchId)
        this.sendStatus(searchId)
        var status = setInterval(function(){ this.sendStatus(searchId) }, 
         30000);
        })
        .catch(err => (this.error = err))

      },

      sendStatus(searchId){},

     }

The initial call to 'sendStatus' function works as expected. However, the setInterval operation results in the following error message:

Uncaught TypeError: this.sendStatus is not a function at eval

Answer №1

In your second call, the context of this is being changed because a new function is being introduced.

If you are working with ES6, an easy solution to this issue is to use an arrow function instead of the function keyword.

    var status = setInterval(() => { this.sendStatus(searchId) }, 
      30000);
    })

If ES6 is not an option for you, then you can use the .bind() function as a workaround, which is explained in this question. Another approach, though not recommended, would be to reassign this to a local variable.

var that = this;

Then within your callback function, you can use that.sendStatus.

Answer №2

To make sure your setInterval works correctly, use an arrow function like this:

setInterval(() => this.sendStatus(searchId))

If you want to learn more about arrow functions and how they handle this, check out this informative resource.

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

Guide for incorporating a clickable link into a specific section of a component

I am working with a File component and displaying the name of the file. I would like to add a clickable link to it. if (item.type === "file") { return ( <File name={item.name} /> // I would like to link item.url to this item.na ...

What is the best way to extract a JSON object from a website search using getJSON or similar techniques?

Can anyone provide guidance on utilizing .getJSON() to access JSON-encoded information from a website that is being searched? I've implemented a Google Custom Search API for my site with the aim of retrieving the JSON file from the search results. Fo ...

Limit window scroll event to prevent overload in React using setTimeout

Is there a way to optimize my window scroll event listener by throttling it every 100 milliseconds instead of triggering on every scroll? I tried using setTimeout, but it seems like my current approach just delays the listener by 100 milliseconds rather th ...

What is the best way to duplicate/rename/replace an image in PHP while utilizing form submission and radio buttons?

I am new to PHP and I am working on a feature that allows a user to change an image using radio buttons and form submission. The goal is to copy and rename one of two image files (Open/Closed.jpg) to another location (images/status/Status.jpg) without requ ...

Using JavaScript to enable autocomplete functionality in an ASP.NET combobox

Is there any way to use JavaScript functions with the asp AJAX Toolkit autocomplete combobox? I'm looking for a way to select the selected item text or value on the client side. Thanks, Atif ...

Easily targeting elements and their descendants in jquery: What you need to know!

Within a div, there are nested divs that contain tables and other divs. How can I use jquery to select both the parent div and its children? The parent div has the class "AccordionTitle AccordionTitle-selected". I have attempted the following: var klo=$( ...

Load custom JS with Google

I have integrated the Google Ajax API and now I need to load custom javascript that relies on the libraries loaded by the ajaxapi. What is the best way to accomplish this? ...

What is the method to adjust the dimensions of the browser's inner window or viewport?

When I execute the following function: browser.driver.manage().window().setSize(1000, 1000); The result is that my window size becomes 1000x1000 while the inner window/viewport size changes to 990x918. By inner window size, I am referring to the area of ...

Adjusting AngularJS scroll position based on key presses

I am currently working on an autocomplete feature using AngularJS. I seem to be experiencing a problem with the scrollbar behavior. In the interactive gif provided, you can observe that the scrollbar remains stationary when navigating with the arrow keys. ...

There is no response provided by the function

Here is the code for inserting data into the database. However, it seems to be going into the else section as the response is empty. I have checked by alerting the response, but it remains empty. // Function to add donation via AJAX function ccjkfound ...

Establish a spacing between a pair of geometries in THREE.JS

I need assistance with adjusting the distance between cylinders and sprites generated by this code. What steps can I take to achieve this? const THREE = this.context.three; const textureLoader = new THREE.TextureLoader(); const geometr ...

A secure password must consist of a minimum of 6 characters

I created a validation code for the password and confirm password to ensure they match. There is also a condition that checks if the password length is less than 6 characters, displaying an error message if it is. However, I am facing issues with my code: ...

Is there a way to prevent this React function from continually re-rendering?

I recently created a small project on Codesandbox using React. The project involves a spaceship that should move around the screen based on arrow key inputs. I have implemented a function that detects key presses, specifically arrow keys, and updates the ...

Create a dynamic and interactive website using a combination of jQuery and AngularJS

I recently came across an interesting tidbit on the FAQs of Angular stating that "Angular can use jQuery if it's present in your app when the application is being bootstrapped". This got me thinking, is it considered a best practice to include both j ...

Utilizing vue-chartjs to display a pair of data figures side by side

In my vue application, I utilize vue-chartjs to showcase some data and I incorporate semantic-ui for the layout. My goal is to display two figures side by side on the screen, but unfortunately, I am facing difficulties achieving this. I have attempted us ...

Transfer the contents of one array into the center of another array using JavaScript

I have been looking for answers here, but I can only find solutions for different programming languages. Currently, I am dealing with 2 Uint8 typed arrays. var arr1 = [0,0,0]; var arr2 = [0,1,2,3,4,5,6,7,8,9]; My goal is to replace the contents of arr2 ...

Issue with the date picker UI in react-datetime not displaying correctly?

<Datetime dateFormat={false} className="form-control" onChange={this.handleChange.bind(this)}/> I am currently utilizing the react-datetime library for time selection handleChange(newtime){ this.setState({MTtime: moment(newtime).format ...

Issues with CSS background colors

I am in the process of streamlining my CSS code by consolidating repetitive elements and removing unnecessary lines (I am currently enrolled in a mobile apps course that emphasizes creating web-based hybrid applications using HTML5, CSS, and JavaScript, he ...

Is it possible to create a back button in Javascript or jQuery that only works if the previous page was within the same website

Is there a way to ensure that the 'back' button link only takes you back to pages within the current site? Here is the code I am currently using: $(document).ready(function(){ $('a.back').click(function(){ parent.history.ba ...

The mtree script in external JavaScript is failing to function properly after dynamically inserting elements using jQuery

Here are the images showing a list of data that appears in all rows after the page loads. However, when I add a row using jQuery, the data does not show up. Please refer to image 2. Image 1 https://i.sstatic.net/xzn2c.png Image 2 https://i.sstatic.net/ ...