Reputation: 709
I wanted to do api calls inside nuxt plugin using vuex action. But when i am using await keyword Nuxt is giving me an error saying Parsing error: Unexpected reserved word 'await'.
So, how can i use promise inside my Nuxt Plugin? Here's my associated code ->
export default (context) => async({ store, route, redirect }) => {
const address = store.state.location.selectedAddress
const payload = {}
if (!address) {
navigator.geolocation.getCurrentPosition(
(position) => {
payload.latitude = position.coords.latitude
payload.longitude = position.coords.longitude
const result = await store.dispatch('location/fetchLocation', payload)
console.log(result)
console.log(
store.state.location.details && store.state.location.details.address
)
},
(error) => {
console.log(error.message)
}
)
}
}
Upvotes: 2
Views: 3299
Reputation: 709
Converting function inside navigator.geolocation to promise solved the issue
export default ({ store, route, redirect }) => {
const address = store.state.location.selectedAddress
const payload = {}
if (!address) {
navigator.geolocation.getCurrentPosition(
async (position) => {
payload.latitude = position.coords.latitude
payload.longitude = position.coords.longitude
const result = await store.dispatch('location/fetchLocation', payload)
console.log(result)
console.log(
store.state.location.details && store.state.location.details.address
)
},
(error) => {
console.log(error.message)
}
)
}
}
Upvotes: 1