0👍
The issue is asynchronous execution.
In require_get
, you update this.temp
in the .then()
callback, which is only called when the Promise has resolved. In get_user_info
, you are calling require_get
and then immediately (synchronously) trying to read the data. Because it is fetched and set asynchronously, it is not yet present and you get undefined
.
To fix it, make require_get
an async function and return the data instead of using this.temp
. Then make get_user_info
an async function as well, await the call of require_get
, and assign this.uid
and this.username
to the returned data.
You could also use .then()
if you prefer that to async/await. I have included examples for both.
I assume that this.uid = data['username']
was meant to be this.uid = data['uid']
, so changed that too.
With async/await
import axios from 'axios';
export default {
data() {
return {
uid: '',
username: '',
loaded: false
}
},
methods: {
async require_get(url) {
var token = localStorage.getItem('token');
var config = {
headers: {
'token': token,
}
};
var _url = 'user/dashboard/' + url;
var response = await axios.get(_url, config);
return response.data;
},
async get_user_info() {
var data = await this.require_get('info');
this.uid = data['uid'];
this.username = data['username'];
}
},
mounted() {
this.get_user_info();
}
}
With .then()
import axios from 'axios';
export default {
data() {
return {
uid: '',
username: '',
loaded: false
}
},
methods: {
require_get(url) {
var token = localStorage.getItem('token');
var config = {
headers: {
'token': token,
}
};
var _url = 'user/dashboard/' + url;
return axios.get(_url, config).then((response) => response.data);
},
get_user_info() {
this.require_get('info').then((data) => {
this.uid = data['uid'];
this.username = data['username'];
});
}
},
mounted() {
this.get_user_info();
}
}