get route params in asyncData after router push - vuejs2

I'm trying to get the route params in the asyncData method, it works if I go manually to the route, but if I use router Push method, it doesn't get any params.
this is my asynData method:
async asyncData(ctx) {
const { id } = ctx.app.router.currentRoute.params
await ctx.store.dispatch('user/GET_USER', id)
return {
user: ctx.store.state.user.user
}
},
and this is how I navigate to the respective page:
goToEdit(id) {
this.$router.push({ path: `/users/${id}/edit` })
}

You need to get route from ctx directly. Here a list of context arguments
async asyncData({ route }) {
const { id } = route.params
await ctx.store.dispatch('user/GET_USER', id)
return {
user: ctx.store.state.user.user
}
},

I'm doing it in a similar way but I retrieve params and almost everything from context.
async asyncData(context) {
const plans = await context.$axios.get("business/get-plans", {
params: {
currency: context.query.currency
}
}).then((res) => {
return res.data;
});
Take a look to context.$axios and context.query.

Related

Variable in data section can't get API response value (response.data)

I accessed API to upload image and return the image URL with Vue app. I want to set API response value to imgUrl1 in data section. I' sure getting correct response in console but imgUrl1 is still empty. Anybody idea ?? Thank you so much !
Vue
data () {return
{
imgUrl1:'',→empty
}
},
methods: {
uploadFile1: function () {
var img_file1 = this.$refs.img1.files[0]
var params = new FormData()
params.append('image', img_file1)
params.append('client_name', this.tableSelected)
axios.post("http://127.0.0.1:5000/", params
).then(function (response) {
console.log(response.data)→image url exists
this.imgUrl1 = response.data
}).catch(function (error) {
for(let key of Object.keys(error)) {
console.log(key);
console.log(error[key]);
}
});
}
console.log(response.data)
https://storage.googleapis.com/dashboard_chichat/img/クライアント名/xxxxxxxxnQSkX6Wudy.jpg
try using arrow functions in your then callback so the value of this is your Vue component.
methods: {
uploadFile() {
...
axios.post('', params)
.then((response) => {
this.imgUrl1 = response.data
})
}
}
the equivalent of it without arrow functions is:
methods: {
uploadFile() {
...
const _this = this;
axios.post('', params)
.then(function (response) {
_this.imgUrl1 = response.data
})
}
}

How to call plugin method from component inside asyncData in nuxt js

component: pages/user/_username.vue
export default {
async asyncData({ context, route, $twitter }) {
const userProfile = await $twitter
.getUserProfile(route.params.username)
.then((userProfile) => userProfile.data)
return { userProfile }
},
}
plugin/twitter.server.js
async getUserProfile(username) {
const userProfiles = await axios
.get(
`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${username}&count=100&tweet_mode=extended`,
{
headers: {
Authorization: 'Bearer ' + (await this.fetchAccessToken()),
},
}
)
.then((res) => {
return res
})
.catch((error) => {
if (error.response.status === 401) {
this.cache.set('accessToken', this.fetchAccessToken())
return this.getSampleStatuses()
}
})
return userProfiles
}
This code working on only server side rendering. i want to call client side or server side rendering. how to call on client side
You can access $twitter (assuming you’ve set it up as a plugin) via the root Vue app instance. You access the root Vue app instance via the context, which you have already included in the asyncData call.
Just change:
const userProfile = await $twitter
To:
const userProfile = await context.app.$twitter

Vue JS - How to get function result in methods()

i'm trying to use this kind of structure.
I have my axios calls in a service file and then call them in vue files.
So i have this js file
const DashboardService = {
getStationList() {
let url = '/api/stations/list'
ApiService.get(url) //ApiService is an Axios wrapper
.then(response => {
console.log(response.data) //data are logged, function is called
response.data
})
}
}
export default DashboardService
Then in the Vue File i have this:
import DashboardService from '#/_services/admindashboard.service'
export default {
methods: {
getMarkers() {
let result = DashboardService.getStationList()
console.log(result) //undefined
}},
mounted() {
this.getMarkers()
}
}
I can't understand why result is undefined because che getStationList() function gets called... when the component is mounted the functions should have returned the response... how can i solve this situation?
getStationList is an async function, so you'll need to await it's result (or use then). For example:
async mounted() {
this.markers = await DashboardService.getStationList();
},
Also see this question for more details.
Next, you are missing a return in the implementation of getStationList.
const DashboardService = {
getStationList() {
const url = '/api/stations/list';
ApiService.get(url).then(response => {
return response.data;
});
},
};
or perhaps:
const DashboardService = {
async getStationList() {
const url = '/api/stations/list';
try {
const response = await ApiService.get(url);
return response.data;
} catch (error) {
console.error(error);
return [];
}
},
};
The result is undefined because getStationList is not returning anything.
You can consider turning your api call into an async function that returns the result.
const DashboardService = {
async getStationList() {
let url = '/api/stations/list';
return ApiService.get(url);
}
}
export default DashboardService
And in your component
methods: {
async getMarkers() {
let result = await DashboardService.getStationList();
console.log(result);
}
},
If you don't want to use the async await syntax. You can return a the promise from your service and utilize the result on your component, as so:
methods: {
getMarkers() {
DashboardService.getStationList().then(result => {
console.log(result);
});
}
},

NuxtJs - Cannot read property 'headers' of undefined

I'm a newbie in NuxtJs. I'm trying to implement an external API Call with axios which I get token and store it on cookie. Everything works well in development. But when I try to run npm run generate it gives me errors that I don't know what to do.
When I delete nuxtSeverInit, npm run generate runs smoothly. And after some research, i think that nuxtServerInit that I'm using shouldn't be used. Can anyone please tell me how to make it work.
This is the first project in a new company, so I'm trying to prove myself. Please help me with it. Will you.
Click here for image that shows the error that appears after npm run generate
This is store/index.js file
import Vuex from 'vuex'
var cookieparser = require('cookieparser')
const createStore = () => {
return new Vuex.Store({
state: {
auth: null,
},
mutations: {
update (state, data) {
state.auth = data
}
},
actions: {
nuxtServerInit ({ commit }, { req }) {
let accessToken = null
if (req.headers.cookie) {
var parsed = cookieparser.parse(req.headers.cookie)
if(parsed){
accessToken = parsed.auth
}
}
commit('update', accessToken)
},
}
})
}
export default createStore
middleware/authenticated.js file
export default function ({ store, redirect }) {
// If the user is not authenticated
if (!store.state.auth) {
return redirect('/login')
}
}
middleware/notAuthenticated.js file
export default function ({ store, redirect }) {
// If the user is authenticated redirect to home page
if (store.state.auth) {
return redirect('/app/dashboard')
}
}
login.vue file
validateBeforeSubmit() {
this.$validator.validateAll().then((result) => {
if (result) {
this.button_title = 'One moment ...';
let submitted_user_data = {
'username': this.emailAddress,
'client_id': this.user_uuid,
'password': this.password,
}
MerchantServices.do_user_login(submitted_user_data)
.then(response => {
let access_token = response.data.access_token;
this.postLogin(access_token);
})
.catch(error => {
this.$refs.invalid_credentials.open();
this.button_title = 'Sign in'
});
return;
}
});
},
postLogin: function(access_token_val) {
if(access_token_val != ''){
setTimeout(() => {
const auth = {
accessToken: access_token_val
}
this.$store.commit('update', auth)
Cookie.set('auth', auth)
this.$refs.invalid_credentials.open();
this.button_title = 'Sign in'
this.$router.push('/app/dashboard')
}, 1000)
}else{
alert('hello')
}
},
and the last user login api call which also returns the token.
do_user_login(user){
var user_details = 'username='+user.username+'&client_id='+ user.client_id +'&grant_type=password&password='+user.password+''
return axios.post('myapiurl', user_details )
.then(response => {
return response;
});
},
Acording to Nuxt Docs req is not available on nuxt generate.
You should use nuxt build and than nuxt start after that.

async/await actions in Vuex

I am wondering how to use async/await actions in Vuex. The docs provide this syntax as an example:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // wait for `actionA` to finish
commit('gotOtherData', await getOtherData())
}
}
Following this example, I have:
import Vue from 'vue';
import Vuex from 'vuex';
import * as firebase from 'firebase';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
// other state vars here
resource: null
},
mutations: {
// saveValues
setResource(state, payload) {
state.resource = payload;
}
},
actions: {
async getResource({ commit, dispatch }) {
var resource
console.log('resource1: ' + resource)
Vue.http.get('https://mysite/api/getResource')
.then((response) => {
console.log('get resource')
var data = response.body;
resource = data.access_resource;
console.log('resource2: '+ resource)
commit('setResource', resource);
var foo = store.getters.resource;
console.log('resource3: ' + foo);
}, (error) => {
console.log(error);
});
},
async getSomeApi({ commit, dispatch }) {
console.log('getting api');
await dispatch('getResource');
var resource = store.getters.resource;
console.log('resource4: ' + resource);
Vue.http.get('https://somesite/api/someapi?resource=' + resource)
.then((response) => {
console.log("got something from somesite")
var data = response.body;
// do something with data -> payload
dispatch('saveValues', payload);
}, (error) => {
console.log(error);
});
}
},
getters: {
resource(state) {
return state.resource;
}
}
});
However, even following the syntax example found in the docs, when I run this code, the async/await seem to be completely ignored. When I look at the logs, I see, in the following order:
getting api
resource1: undefined
resource4: null
get resource
resource2: <expected-value>
resource3: <expected-value>
I expect the console.log statements to print out in numerical order. I would appreciate if someone could clarify what I am doing wrong.
You're not awaiting the Vue.http.get() promise in the getResource() method, so await dispatch('getResource') will resolve before the HTTP request has resolved.
Trimmed down:
async getResource() {
let response
try {
response = await Vue.http.get('https://mysite/api/getResource')
} catch (ex) {
// Handle error
return
}
// Handle success
const data = response.body
}