reactjs.nettypescriptaxios

Accessing Data from my axios get response not working


Can someone point out where am going wrong?

I have a simple API get request. This gets data fine from my API:

const GetMedicalPackages = async (props:IGetMedPack)=>{
    const token = props.token
   
    const data = axios({
        method:"get",
        responseType:"json",
        url : baseURL + "medicalPackage", 
        headers: { "Authorization": `Bearer ${token}`}
      })
      await data;
      return data.then((response:IMedicalPackageData| undefined)=>{
        return response
      })
} 

This returns data like this:

Data from API

Now trying to access the data with this code returns with this code always returns and undefined

useEffect(() => {
    //async function fetchMyData() {
    GetMedicalPackages({ token }).then((response) => {
      if (response) {
        const options = response.data.map((row) => {
          console.log(row.MedicalInsurancePackage);
          return row.MedicalInsurancePackage;
          //console.log(row);
          //options.push(row.MedicalInsurancePackage);
        });
        //setMedPackage(options);
        console.log(options, response.data);
      }
    });

options values

I suspect it to do with the object that returned in each row but I might be wrong.

Can someone point out what is wrong, please? Thanks

I have tried foreach and various techniques but nothing.

To get the array of strings, just for clarity, the problem is not the axios call giving me the data. I can see data fine. But try to use the data returned is the problem. console log shows me the data. But as soon as I try to map it, I get undefined. Please see screenshots.

Console log shows this:

activePackage: true
medicalInsurancePackage: "Standard"
medicalInsurancePackageDesc: "S Standard"
medicalInsurancePackageID:1
[[Prototype]]:Object

but console log row.medicalInsurancePackage returns "undefined"


Solution

  • Looks like your are missunderstanding how Promise are working. consider doing:

    const GetMedicalPackages = async (props) => {
      const token = props.token;
    
      return await axios({
        method: "get",
        responseType: "json",
        url : baseURL + "medicalPackage",
        headers: { Authorization: `Bearer ${token}` },
      });
    };