Vue.js Interval Functionality Malfunctioning

I'm brand new to Vuejs and I'm attempting to set an interval for a function, but unfortunately it's not working as expected. Instead, I am encountering the following error:

Uncaught TypeError: Cannot read property 'unshift' of undefined

Oddly enough, a standard alert box works just fine. It seems like the variable cannot be accessed properly. How can I ensure that I can access the variable message? You can find my code in the JSFiddle link below.

JS

new Vue({

    el: '#app',

    data: {

        message: {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'},
        
        messages: [
            {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'tw'},
            {message: 'Lorem ipsum', name: 'John Doe', fblike: 0, share: 0, retweets: 1, likes: 0, image: '', adress: '', platform: 'fb'},
        ],

        headerShow: false,
        programShow: false,
        sliderShow: true

    },

    methods: {

        addTweet: function() {
            if(this.message.message){
                this.messages.unshift(this.message);
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
            }
        },

        setTweet: function() {

            setInterval(() => {
                this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
                this.messages.unshift(this.message);
            }, 5000);

        }

    }

});

https://jsfiddle.net/fLj5ac0L/

Answer №1

The reason why the correct context was lost in the setInterval function is because it is not bound to the Vue object, causing this.message to return undefined. One solution is to use an arrow function or store the context in another variable.

setTweet: function() {

    setInterval(() => {
        this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
        this.messages.unshift(this.message);
    }, 5000);


}

or

setTweet: function() {
    var self = this;
    setInterval(function() {
        self.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
        self.messages.unshift(self.message);
    }, 5000);


}

Answer №2

When using function(){} to call outside variables, keep in mind that the function creates a new scope. Consider modifying your code as shown below:

setTweet: function() {
  var that = this;
  setInterval(function() {
    that.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
    that.messages.unshift(this.message);
  }, 5000);
}

Alternatively, you can use an arrow function like this:

setTweet: function() {
  setInterval(() => {
    this.message = {message: '', name: '', fblike: 0, share: 0, retweets: 0, likes: 0, image: '', adress: '', platform: 'tw'};
    this.messages.unshift(this.message);
  }, 5000);
}

For more on JavaScript variable scope, refer to this question: What is the scope of variables in JavaScript?

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

How can we call a function in HTML from an external JavaScript file?

I am attempting to utilize a function that I have defined in my .js file within my HTML document. js/newsalerts.js function decodeHTML(html) { //https://stackoverflow.com/a/2989105/4650297 var tempDiv = document.createElement("DIV"); tempDiv. ...

Implementing an All-Routes-Except-One CanActivate guard in Angular2

In order to group routes within a module, I am aware that it can be done like this: canActivate: [AuthGuard], children: [ { path: '', children: [ { path: 'crises', component: ManageCrisesComponent }, ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

Interacting with a Hapi JS API through a distinct Vue JS Frontend. The data in request.payload is not defined

As I take my first steps on Hapi JS, I am facing the challenge of connecting my app to a SQL Server DB. My current task involves sending login data from a Vue CLI JS frontend to a Hapi JS Api using axios. The login process essentially consists of a "SELEC ...

What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{ var bool :boolean =false this.companyService.query().subscribe((result)=>{ for (let i = 0; i < result.json.length; i++) { try { if( id == result.json[i].user.id) ...

The concept of nested views in Angular UI-Router allows for a

How can I successfully implement nested views, where after logging in the user is redirected to in.html, and all links within in.html are directed to a ui-view? Currently, all links redirect to a new page. index.html <!-- more HTML --> <body ng- ...

Changing the index of an item in an array in React based on order number

Hey there, I'm a new Reactjs developer with a question. It might be simple, but I'm looking to learn the best practice or optimal way to change the index of a selected item in an array based on user input. Essentially, the user will provide a num ...

jQuery Show/Hide Not Working Properly

I'm attempting to showcase one Tweet at a time and have it rotate through different tweets. I'm facing an issue where it works correctly on one type of page, but not on the other. Could this be due to a CSS precedence rule overriding the function ...

Are there specific files or classes that store constants for different keyboard events?

When working in Angular, I often bind data with a host listener using code similar to the example below: @HostListener('window:keyup', ['$event']) onKeyUp(event: KeyboardEvent) { if (event.keyCode === 13) { this.onEnterClicked(ev ...

Adjust the navigation menu to display or hide as the page is being scrolled

Implementing an offset to display/hide the navigation menu when the page is scrolled 100px. Attempted to modify from lastScroll = 0 to lastScroll = 100 but it did not work as expected. Jquery: Fiddle // Script lastScroll = 0; $(window).on('scroll&ap ...

Conceal any child elements that are cut off as a result of the overflow hidden property

Despite the numerous questions on this topic, none provide a suitable answer. In this scenario, the overflow hidden property is applied to the parent div. The goal is to display only the child elements that are fully visible within this container. In the ...

Navigating through Laravel's API

My software is quite small and I utilize both laravel and vue.js. I am curious about the variance between routing via api.php and web.php within the routes folder. Could someone please enlighten me on the distinctions between these two scenarios? ...

Error encountered while attempting to save a Mongoose post on Heroku, although it is successful

My aim is to post to my MongoDB Atlas database using node, express, mongoose, and Heroku. While a Postman POST request with Raw JSON body: { "title": "heroku post", "description": "post me plsssss" } works f ...

Obtain the total number of items in the list based on the applied filters and dynamically

My application initially shows the total number of posts based on the server's response. However, users have the option to filter these posts, and I need to dynamically update the post count according to the filtered results. inputFilter:function() ...

How can I animate scrolling up or down using jQuery and CSS?

I have a a element that triggers an action when clicked: <a href="#" class="hel" onclick="YPCP1_();">Scroll down</a> Also, function YPCP_(){ var scroll = $(window).scrollTop(); window.scrollTo(0, 600); } The function successfully sc ...

Issue encountered in loading css and js folders during the build of the Angular2 application due to the files not being found

I have developed an Angular 2 application that utilizes Node.js server APIs. After building the app using nd b, the files were generated in the dist folder. Where should I specify the production URL for the build so that all CSS and JS files load properly? ...

By using Yii2, you can pass an id to the URL by simply clicking on a

I am struggling with sending the post_id from a div containing text content (retrieved from a database) to a URL in order to render a view page displaying the entire content. I am using Yii2 and believe I need to use JavaScript for this task, but I am unsu ...

What is the best way to add a `<div>` before or after a specific `<p>` element based on the client's height?

I am facing an issue with inserting a div before a paragraph element based on the given clientHeight. Specifically, I need to locate the closest paragraph element from the specified clientHeight and then add a div before or after that particular element. ...

Is there a way to remove the "next" button from the last page in a table?

I'm currently working on implementing pagination for my table. So far, I have successfully added both the "next" and "previous" buttons, with the "previous" button only appearing after the first page - which is correct. However, I am facing an issue w ...

Breaking up an array into smaller chunks with a slight twist

Here's a straightforward question. I have an array, like this: let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], maxChunkLength = 3; I am looking to divide this array into multiple arrays as follows: [[1, 2, 3], [3, 4, 5], [5, 6, 7], [7, 8, 9], [9, ...