Reputation: 107
I use VueJS for a project and Axios for API call. I don't know how to execute this code once. When I go in my home page this code is executed, I go to another page, I go back and this code is executed again. How to cancel execution ?
mounted () {
axios
.get( config.API.projects )
.then(response => {
this.SET_PROJECTS( response.data );
const projects = this.$store.getters["projects/projects"];
projects.forEach( project => {
this.SET_SKILLS( project.skills )
});
this.SET_SHOW_LOADER( false );
})
.catch( ( error ) => {
console.log( error );
alert( "Une erreur est survenue, merci de contacter par mail l'administrateur de ce site" )
});
},
Upvotes: 1
Views: 401
Reputation: 4406
Assuming Your VUEX getter "projects/projects"
is an array, and is not populated before the call, you can just do a check to see if it has any data. If it is empty (length equal to zero
) you want to get the data and populate it with it. Next time you enter this view, the check will fail, since the store is already populated with the results. (length of projects is greater than 0
)
mounted () {
const projects = this.$store.getters["projects/projects"];
if (projects.length === 0) {
axios.get( config.API.projects ).then(response => {
this.SET_PROJECTS( response.data );
projects.forEach( project => {
this.SET_SKILLS( project.skills )
});
this.SET_SHOW_LOADER( false );
})
.catch( ( error ) => {
console.log( error );
alert( "Une erreur est survenue, merci de contacter par mail l'administrateur de ce site" )
});
}
},
Bonus tip: Be carefull with using .catch
. I assume you want to "catch" only if there is any errors with getting the data with axios. What you are also doing, it actually catching/silencing every error from the line axios.get(...
to the line .catch
. This means that if let's say you get an error inside the .then
function, eg: "SET_PROJECTS" is not an function
and your app breaks, you will not get it in the console
In your case, you will. But only because you console.log
the error parameter from the .catch
. If you did not do this, you would never know there was any errors.
To fix this, simply change .catch
to the 2nd parameter of the .then
function:
if (projects.length === 0) {
axios.get( config.API.projects ).then(response => {
this.SET_PROJECTS( response.data );
projects.forEach( project => {
this.SET_SKILLS( project.skills )
});
this.SET_SHOW_LOADER( false );
}, error => {
console.log( error );
alert( "Une erreur est survenue, merci de contacter par mail l'administrateur de ce site" )
})
}
Upvotes: 1