0

I'm trying to get access to my store data from a mounted method of my component. It works fine if I try it with a not mounted method. After I read a bit it makes sense that I've no access, but is there any other way I didn't find yet?

methods: {
    testEvent() {
        // works
        let players = this.$store.state.players;
        console.log(players);
    },
    socketEvent() {
        // Uncaught TypeError: Cannot read property 'state' of undefined
        socket.on('dice_data', function(data) {
            let players = this.$store.state.players;
            console.log(players);
        });
    }
},
mounted() {
    this.socketEvent()
}

Thank you

bonblow
  • 1,151
  • 6
  • 19
  • 28

1 Answers1

3

Issue is with this inside function

You can solve like this:

   socketEvent() {
        socket.on('dice_data', (data) => {
            let players = this.$store.state.players;
            console.log(players);
        });
    }

or if you prefer to write function, instead of arrow function you can also do like this:

   socketEvent() {
        let self = this
        socket.on('dice_data', function(data) {
            let players = self.$store.state.players;
            console.log(players);
        });
    }
latovic
  • 899
  • 6
  • 11