Is it possible to trigger a mutation from an interceptor in Vue? Specifically, I want to trigger the logout
mutation whenever Axios encounters an http 403 error.
I have imported Vuex mutations and mapped them as I usually do, but I am struggling to access them within the Axios interceptor error function. I have added my interceptor configuration in the created() method of App.vue.
I have attempted solutions from other sources without success, possibly because my project uses modules and the Axios config is within a created()
method.
- This Reddit thread discusses Axios config in a separate file - is this recommended?
- This Stack Overflow question addresses accessing Vuex storage mutation inside Axios interceptor without using modules.
App.vue
<script>
import { mapMutations } from "vuex";
import axios from 'axios';
export default {
methods: {
...mapMutations(["logout"])
},
created(){
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
if (error.response.status === 403) {
this.logout()
.then(() => {
this.$router.push("/");
})
}
});
}
}
</script>
EDIT Here is a screenshot of the results based on the provided answers: https://i.sstatic.net/uryJP.png