airsoftFreak
airsoftFreak

Reputation: 1608

How to do mapGetters in asyncData? Nuxt

My goal is to pass a getter object inside asyncData, because I need to access the state to pass data to axios

Code example

export default {
   async asyncData() {
      let result = await $axios.$post('/api/test', { data: this.totalPrice })
   },
   computed: {
      ...mapGetters(["totalPrice"])
   }
}

As you can see I want to access getter object in asyncData However I got

enter image description here

Upvotes: 0

Views: 5240

Answers (2)

dreijntjens
dreijntjens

Reputation: 4825

Methods should be placed into methods to have the vue context:

export default {
   methods : {
      async asyncData() {
         let result = await $axios.$post('/api/test', { data: this.totalPrice })
      }
   },
   computed: {
      ...mapGetters(["totalPrice"])
   }
}

If you want to do it onload use mounted (https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram)

export default {
   async mounted() {
      let result = await $axios.$post('/api/test', { data: this.totalPrice })
   },
   computed: {
      ...mapGetters(["totalPrice"])
   }
}

Upvotes: -2

Phil
Phil

Reputation: 164798

As indicated in the documentation...

Warning: You don't have access to the component instance through this inside asyncData because it is called before initiating the component.

Instead, use the context object provided

async asyncData ({ store }) {
  const body = { data: store.getters.totalPrice }
  const { data } = await $axios.$post('/api/test', body)
  return data
}

Upvotes: 3

Related Questions