Home » vue » socket.io and vue.js fetching data

socket.io and vue.js fetching data

Posted by: admin November 26, 2021 Leave a comment

Questions:

I am trying to fetching the data of vue.js using this

fetchData: function () {
                socket.emit('getAllSongs')
                socket.on('allSongs',function(data) {
                    this.songs = data
                });

          }

FetchData is called when the vue app is created

created: function () {
            this.fetchData();
        }

But when I try to call the variable songs outside socket.on it stills empty.

What could I do?

Answers:

Try changing you fetchData function to this:

fetchData: function () {
    socket.emit('getAllSongs')
    var that = this;
    socket.on('allSongs',function(data) {
        that.songs = data
    });
}

The reason is the value this is different in the callback context and is not the component object which you expect it to be.

###

I think you need to bind this to the end of your function or to use ES6 arrow syntax =>

socket.on('allSongs',function(data) {
    that.songs = data
}.bind(this));

socket.on('allSongs',data => {
    that.songs = data
});