reactjsjsonapiaxios

Unable to fetch nested values from axios api response


I am able to fetch the response.data object but when I try to fetch the values inside it, I get undefined as out put. Here is my code

import axios from 'axios';
import { injectable } from 'inversify';
import "reflect-metadata";

interface Configuration {
  EnableForgetPassword?: string;
}

interface Data {
  configuration?: Configuration[];
  permissions?: string[];
}

interface ConfigData {
  data: Data;
 
}

@injectable()
class ConfigService {
  private _config: ConfigData = {
    data: {
      configuration: [{ EnableForgetPassword: "False" }],
      permissions: []
    },
    
  }
  private _permissions: string[] = []
  private _configuration: any = {};

  async loadConfigData(): Promise<void> {
    
      const response = await axios.get<ConfigData>('https://run.mocky.io/v3/74946531-e762-4f42-990d-2e73b73f9176');
      const config = response.data; 
      
      console.log(config);
      console.log(config.data.permissions); // throws error
  
}
}

here is my response json

{ 

data: {
  
  configuration:[{"EnableForgetPassword":"True"}],
  permissions:["Global.Settings","User.Create"]
  
  }
}

I'm getting this error:

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'permissions') at ConfigService.loadConfigData


Solution

  • JSON properties need to be in "double quotes", so your JSON is not valid and Axios isn't able to handle it as JSON. This is what your server should be returning:

    {
      "data": {
        "configuration": [
          {
            "EnableForgetPassword": "True"
          }
        ],
        "permissions": [
          "Global.Settings",
          "User.Create"
        ]
      }
    }