I am trying to initiate an Axios Client for my React app. I want to use the authenticated client to make requests. The current setup looks as followed. Due to the session service being async to check for a cached token and validating it against the server the initiation of the API Client is also async. This results in the client in the ExampleService being undefined when constructed too early. The goal is to keep the Services as self contained as possible.
class ApiClientService {
client: AxiosInstance
async init() { // gets called asap on launch
await sessionService.init()
this.client = axios.create({
baseURL: config.host,
timeout: 1000,
headers: { Authorization: `token ${sessionService.getToken()}` }
})
}
getClient() {
return this.client
}
...
}
class ExampleService {
private client = apiService.getClient()
async doSomething() {
return this.client.get('/something')
}
}