I am working on a ReactJS application, which uses many API calls to get data from the server. These API calls are organized into multiple classes and all of them use another class which issues a HTTP request using Axios.
Example markup and flow: (this is hand typed to keep it simple, please ignore any minor mistake or omissions)
class MyComponent extends Component{
componentDidMount(){
this.props.getData(//parameters//); //getData is an action bound via react-redux connect.
}
}
export const getData = (//parameters//) => (
dispatch: any
) => {
return new Promise((resolve, reject) => {
//Some business logic
let axiosService = new axiosService();
axiosService .get(//parameters//).then((data: any) => {
dispatch({
type: "RECEIVE_DATA",
payload: data
});
resolve();
});
});
};
export default class AxiosService {
config: AxiosRequestConfig;
url : string;
constructor() {
this.url = "http://localhost:8080/api/";
this.config = {
headers: {
//I want to inject Authorization token here
},
responseType: "json"
};
}
get = () => {
return new Promise((resolve, reject) => {
resolve(axios.get(this.url, this.config));
});
};
}
Now I want to inject auth token as Authorization header when AxiosService makes an API call. This token is available in redux store. How can I access redux store in my service?
I can pass the token as a parameter to AxiosService get call, but that is messy. Based on my reading custom thunk middleware might help me here, but not sure how to update my service call. I have many actions, that need to use AxiosService.