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

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

What is the best way to locate a table of a specific class using jQuery selectors?

Is there a way to specifically target a table with the class "d" using jQuery selectors? I'm having trouble making it work... var dTableTags = $(".d table"); For instance, an example table would look like this... <table id="thetable" class="d"&g ...

The catch all route in Next.js seems to be malfunctioning when paired with the getStaticPaths function

Why is the Next.js catch all route not working as expected with the getStaticPaths function? The documentation states that I should be able to navigate to both t/a.cat and t/a.cat/a.id, but it only seems to work for the latter. What could be causing this ...

How can I display milliseconds from a date in Angular2+?

I recently encountered an issue while working with a custom pipe that was used to display time. I attempted to modify it so that it could also show milliseconds: {{log.LogDate|jsonDate|date:'dd.MM.yyyy &nbsp; HH:mm:ss.sss'}} Here is the cod ...

Tips for updating JS and CSS links for static site deployment

As I develop my static site using HTML files served from a simple web server, I want to use local, non-minified versions of Javascript code and CSS files. However, when it comes time to deploy the site, I would like to refer to minified versions of these s ...

Step-by-step guide on clipping a path from an image and adjusting the brightness of the remaining unclipped area

Struggling to use clip-path to create a QR code scanner effect on an image. I've tried multiple approaches but can't seem to get it right. Here's what I'm aiming for: https://i.stack.imgur.com/UFcLQ.png I want to clip a square shape f ...

My goal is to retrieve the top three highest rated products

// @route GET /api/products/top // @desc Retrieve top-rated products // @access Available to the public router.get( '/best', asyncHandler(async (req, res) => { const bestProducts = await Product.find({}).sort({ rating: -1 }).limi ...

Unable to store object data within an Angular component

This is a sample component class: export class AppComponent { categories = { country: [], author: [] } constructor(){} getOptions(options) { options.forEach(option => { const key = option.name; this.categories[k ...

Combine collapse and popover in Bootstrap 3 for enhanced functionality

I'm facing some issues trying to use the badge separately from the collapse feature. $(function (e) { $('[data-toggle="popover"]').popover({html: true}) }) $('.badge').click($(function (e) { e.stopPropagation(); }) ) Check o ...

Plugin for jQuery that smoothly transitions colors between different classes

After searching through numerous jQuery color plugins, I have yet to discover one that allows for animating between CSS class declarations. For instance, creating a seamless transition from .class1 to .class2: .class1 { background-color: #000000 } .class ...

adjust variable increment in JavaScript

As I work on developing a Wordpress theme, I have encountered an issue with incrementing a load more button using Javascript. This is my first time facing this problem with a javascript variable, as I don't always use Wordpress. The variable pull_page ...

Refresh the Vuex store using the main process of Electron

Is there a way to update a vuex store by committing changes from the main process? Here is an example: In the main thread: import store from '../store' ipc.on('someevent', (event, args) => { // do something with args store ...

php script within a literal .tpl file

Is there a way to perform a json_encode within a literal javascript block in the context of a Smarty template? {literal} <script> function openWin() { var O = {php} echo json_encode($obj);{/php}; // syntax error ...

How can you incorporate a custom button into the controlBar on videoJS in responsive mode?

The video player I have created using videoJS includes custom buttons in the control bar. These buttons are not clickable when viewed on mobile or tablet devices without forcing them to work. let myButton = player?.controlBar.addChild('button'); ...

Ways to recycle the output of the three.js fragment shader

Recently delving into GLSL shaders in three.js, I am currently experimenting with creating a simple and efficient blur effect on a mesh texture. Below is the fragment shader code I have been working on: void blurh(in vec4 inh, out vec4 outh, int r) { ...

The inner workings of v8's fast object storage method

After exploring the answer to whether v8 rehashes when an object grows, I am intrigued by how v8 manages to store "fast" objects. According to the response: Fast mode for property access is significantly faster, but it requires knowledge of the object&ap ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...

Getting AJAX parameters from Angular in Node/Express Js

I am encountering an issue with my factory, which sends an ajax userId call to my node server. usersModel.getUser = function(userId){ return $http({ method: 'GET', url: 'http://localhost:3000/users/details', ...

Different approach for binding in Vue.js

Seeking Alternatives I am curious to find out if Vue.js offers a different approach for outputting data beyond the conventional curly braces. Is there a syntax similar to Angular's ng-bind directive that I could utilize? Although Vue.js primarily ut ...

What is the process of generating a VectorSource in OpenLayer 6.5 using a JavaScript object?

I'm in the process of developing a web application that utilizes OpenLayer 6.5. I need to dynamically mark certain locations without storing ".geojson" files on the server. Any suggestions on how I can achieve this? When attempting to create a Vector ...