I want to use data from the axios response. I know it returns a promise object, but how do I manipulate the data in .then
, and make it accessible? Do I need to add a callback function to my getData
method? I want the properties to be accessible and stored in a variable outside the axios request, and in another class, and not just console.log.
I want to store variables from data.response.name
etc. This is what I have tried so far, but I get undefined
or promise: Object
export class myClass {
public async getData() {
return axios.get(url)
.then(response => response.data)
.catch((error) => {
console.log(error);
});
}
public async getName() {
return this.getData().then((res:any) => {
return res.name;
});
}
}
Outside class:
const myData = new myClass().getName().then(res => res);
**I have update my question, and tried to do the answer as described here, but i still get undefined:* How to access the value of a promise?
public async getData() {
const promiseB = this.promiseA().then(function (result) {
return result;
});
promiseB.then(function (result) {
// here you can use the result of promiseB
result = result.name;
return result;
});
}