Axios not setting data - vue.js

I'm trying to set data from an axios response but it seems to me like "this" is only in the scope of the axios function. I have tried different variations of the same code that I've seen on other posts, but none are working.
data: () => ({
storeKey: 'dayspanState',
calendar: Calendar.months(),
readOnly: false,
defaultEvents: [],
ticket_event: [],
}),
created(){
this.get_tickets();
console.log(this.ticket_event);
},
methods:
{
get_tickets(){
axios.get('/api/get_patching_tickets')
.then(function (response) {
this.ticket_event = response.data;
}.bind(this));
},
}
Second trial
created(){
var self = this;
axios.get('/api/get_patching_tickets')
.then(function (response) {
self.ticket_event = response.data;
});
console.log(this.ticket_event);
}
Any help would be appreciated.

Try rewriting your function like:
created(){
axios.get('/api/get_patching_tickets')
.then((response) => {
this.ticket_event = response.data;
}).finally(() => {
console.log(this.ticket_event);
});
/* WARNING: the following console will not work as expected
as the local value is set after the successful call
while this is fired immediately after created is called
*/
console.log(this.ticket_event);
}

The callbacks you passed to .then in axios.get are fine. I see the only problem with your code is that it logs this.ticket_event right after calling this.get_tickets() - an asynchronous operation, so it'll not log the updated value after the api call finish because this.get_tickets() operates asynchronously:
this.get_tickets(); // is an async operation
console.log(this.ticket_event); // will not get the most updated value of this.ticket_event
Try this to see if it works:
data() {
return {
storeKey: 'dayspanState',
calendar: Calendar.months(),
readOnly: false,
defaultEvents: [],
ticket_event: [],
}
},
methods: {
get_tickets() {
return axios.get('/api/get_patching_tickets')
.then(response => {
this.ticket_event = response.data;
});
}
},
created() {
this.get_tickets().finally(() => {
console.log(this.ticket_event);
});
}

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 do i add another function in vue.js

How do i add multiple get posts in Vue.js.
I already have one post that I'm getting fine but I'm not sure how to add multiple post functions.
This is what i have so fare.
<script>
new Vue({
el: '#app',
data () {
return {
searchQuery: null,
info: null,
loading: true,
errored: false
}
},
mounted: function () {
axios.post('https://api.npms.io/v2/search?q=vue')
.then(response => {
this.info = response.data
console.log(this.info)
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
}
})
</script>
If you want to do the calls one after the other then
you can just nest the second axios call inside the first one.
In this way you can keep nesting to multiple levels
axios.post('https://api.npms.io/v2/search?q=vue').then(response => {
this.arrayOne = response.data
axios.post('https://api.npms.io/v2/search?q=vue').then(
response => this.arrayTwo = response.data
);
});
OR
You can try using async/await
Below is an example where I have used the response of first request to make the second request.
async mounted() {
try {
const response1 = await axios.get('/user/12345');
this.arrayOne = response1.data;
const response2 = await axios.get(`/user/12345/${this.arrayOne.name}/permissions`);
this.arrayTwo = response2.data;
} catch(e) {
console.log(e);
}
}
I would suggest taking a look at Promise.all() (link to MDN docs). You could do something like:
Promise.all([
axios.post('https://api.npms.io/v2/search?q=vue'),
axios.post('https://example.com/...')
]).then(responses => {
console.log(responses);
// will output an array with responses[0] equals to the data of the first call and responses[1] equals to the data of the second call
})
// Add your catch and finally clauses here...
The benefits of this approach is that your calls are made in parallel but the then clause will only be reached when they both ended.

Vuex state is sometimes empty (undefined), especially when I refresh the page and sometimes it works

Vuex state is sometimes empty (undefined), especially when I refresh the page. And sometimes it works.
action:
getSkills(context) {
let url = "/skills";
const headers = {
"x-api-key": process.env.VUE_APP_SIRH_X_API_KEY,
Authorization: localStorage.getItem("access_token"),
};
return axios({
method: "get",
url: url,
headers: headers,
}).then((response) => {
context.commit("getSkill", response.data.data.skills);
}).catch((e) => {
console.log(e);
});
},
getter:
Skills: (state) => state.Skills,
mutation :
getSkill(state, skills) {
state.Skills = skills;
},
state :
Skills: [],
and the vue :
computed: {
...mapState({}),
...mapGetters(["Candidate", "Skills"])
},
mounted() {
this.getSkills();
this.id = this.$route.params.id;
this.Skills.forEach(element => this.skill_list.push(element.skill_name));
},
methods: {
...mapActions(["attachSkillCandidate", "getSkills"]),
}
Can anyone help me to solve this issue ?
Thanks!
The getSkills action is performing an asynchronous request. You need to wait for the request to finish before you can access this.Skills otherwise the data will not be set yet.
You need async and await (the "modern" solution):
async mounted() {
await this.getSkils();
this.id = this.$route.params.id;
this.Skills.forEach(element => this.skill_list.push(element.skill_name));
}
or:
mounted() {
this.getSkils().then(() => {
this.id = this.$route.params.id;
this.Skills.forEach(element => this.skill_list.push(element.skill_name));
});
}

Cannot read property of "then" of undefined APOLLO GRAPHQL

I'm having a trouble and i'm stuck. I used to replicate this on my other codes but this method doesn't work on apollo. Here is my method using the apollo on my vue.js.
handleLikePost() {
const variables = {
postId: this.postId,
username: this.user.username
};
this.$apollo.mutate({
mutation: LIKE_POST,
variables,
update: (cache, { data: { likePost } }) => {
const data = cache.readQuery({
query: GET_POST,
variables: { postId: this.postId }
});
data.getPost.likes += 1;
cache
.writeQuery({
query: GET_POST,
variables: { postId: this.postId },
data
})
.then(({ data }) => {
// const updatedUser = {
// ...this.user,
// favorites: data.likePost.favorites
// };
//this.$store.commit("setUser", updatedUser);
console.log(this.user);
console.log(data.likePost);
})
.catch(err => console.error(err));
}
});
}
I think the problem is you are not returning something from;
cache.writeQuery()
That's why .then({data}) is not getting something from writeQuery()

Vuejs axios count results after they have been returned

I'm trying to find the correct way to get the number of returned results from my async axios get query but not getting anywhere so hoping someone can assist
My code is as follows
mounted() {
axios.get('http')
.then(response => {
this.myItems = response.data // this works
countResults(response) //this doesn't seem to
.catch(error => console.log(error))
})
},
filters:{
countResults: function(value){
return value.length;
}
I then call as follows
<p>Number of Entries: {{countResults}}</p>
Thanks
You can call the filter method in this way
this.$options.filters.countResults(response)
To solve your problem you need to store the response. You can do that in this way
mounted() {
axios.get('http')
.then(response => {
this.myItems = response.data // this works
this.responseData = response.data
}).catch(error => console.log(error))
},
data: {
responseData: []
},
filters: {
countResults: function(){
return this.responseData.length;
}