Matt W
Matt W

Reputation: 12434

Vuex store cannot be used inside axios handler

I have method being successfully called by a button in my Vue component:

  methods: {
    goTestMe() {
      console.log(this.$store.state.lang+' 1')
      let url = 'some api url'
      let headers = { headers: { 'Content-Type': 'application/json' } }
      
      this.$axios
        .get(url, headers)
        .then(function(response) {
          console.log('here')
          console.log(this.$store.state.lang+' 2')
        })

The problem is that the output of this is:

en-us 1
here

When it should be:

en-us 1
here
en-us 2

Clearly, the reference to this.$store.state is failing in the then() handler of the axios call.

Why is this? How can I send data received by my axios request to the Vuex store?

Upvotes: 1

Views: 251

Answers (1)

Joseph
Joseph

Reputation: 6269

when you add the callback in the normal function you can't access the global object so you need to change it to an arrow function

 methods: {
    goTestMe() {
      console.log(this.$store.state.lang+' 1')
      let url = 'some api url'
      let headers = { headers: { 'Content-Type': 'application/json' } }
      
      this.$axios
        .get(url, headers)
        .then((response) => { // change it to arrow function
          console.log('here')
          console.log(this.$store.state.lang+' 2')
        })
}

Upvotes: 2

Related Questions