I am using axios in react project. I am creating the class for api call with axios. I am creating axios config for reusing. In the first api.js console.log show data. But in subject.js data is undefined. I tried rewritte method getData as async but in subject.js I have got The 'await' operator can only be used in an 'async' function. So I looking another way.
//class api.js :
getInstance(isAuthorized = null)
{
if(this.instance == null)
{
if(isAuthorized)
{
this._headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': `Bearer ${this.authManager.getToken()}`
};
}
if(isAuthorized == null)
{
this._headers = {
'Accept': 'application/json',
'Content-Type': 'application/json'
};
}
this.instance = axios.create({
baseURL: this.baseUrl,
timeout: 1000,
headers: this._headers
});
return this.instance;
}
else
{
return this.instance;
}
}
getData(action,payload,isAuthorized) {
try {
let data = undefined;
this.getInstance(isAuthorized).get(action).then(response =>{
data = response.data;
// here its ok data initialized
console.log(data);
return data;
});
}
catch (err) {
return err;
}
}
//class subject.js
export default () => {
const api = new Api();
// console log writte undefined
console.log(api.getData('/subject/get',null,true));
....