I am building an Vue.js app that relies heavily on api calls. I am using axios to make call. I am using a pattern similar this. Basically I have created a service that will be shared by all the components. Following is the service:
//api-client.js
import axios from 'axios'
import store from '../src/store'
let authKey = store.getters.getAuthKey
export default axios.create({
withCredentials: false, // This is the default
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: "Basic "+authKey
}
})
Now notice I am using a getter to get auth token for the vuex store and seting it in the service.
I will use this service like:
//App.vue
<template>
<div>
<!-- some code -->
</div>
</template>
<script>
import apiClient from "../api-client.js"
export default {
mounted(){
apiClient.get("#url").then(()={
// Do Something
})
}
}
</script>
<style lang="scss">
</style>
The situation is, auth key changes every now and then, so I have a setting that will update the auth key in the store. The setting updates the auth key in store successfully, but the key in api-client.js is not updated. It is loaded only once and the update in the store is not cascaded to this api-client.js.
Is there any pattern to solve this? Please suggest.