I am currently working on a Vue.js application that heavily relies on API calls, utilizing axios to make these requests. I have implemented a similar pattern found at this link. Essentially, I have created a service that will be shared across all components. Here is the structure of 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
}
})
One important detail to note is that I retrieve the authentication token using a getter from Vuex store and incorporate it into the service.
This service is then utilized as follows:
//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 issue arises when the authentication key changes periodically, which triggers an update in the store. However, despite successful updating of the key in the store, the key in api-client.js remains static. It seems that the service loads only once and doesn't reflect subsequent updates made to the key in the store.
Does anyone know of a pattern or technique to address this problem? Any suggestions would be greatly appreciated.