2

I want to get CAD value from https://api.exchangeratesapi.io/latest I have already used so many types of code, and it says that "TypeError: Cannot read property 'CAD' of undefined" Really need your help, thank you very much.

It outputted all the Currencies if I console this code

((this.state.data as any).rates)

but when i want to get CAD currencies, it says the error

I have tried these codes :

((this.state.data as any).rates as any).CAD
(this.state.data as any)["Rates"]["CAD"];
(this.state.data as any)["Rates"].CAD;

The way I get the data is

interface IState {
  data?: object | null;
  isCurrency?: boolean;
  Currency?: string;
  Rate?: number;
}

export default class Header extends Component<{}, IState> {
  service: UserService = new UserService();
  state = {
    isCurrency: false,
    Currency: "USD",
    Rate: 1,
    data: [] = []
  };

  async componentDidMount() {
    let result = await this.service.getAllCurrency();
    this.setState({
      data: (result as Pick<IState, keyof IState>).data
    });
    console.log(result);
  }
}

1.4591 (Based on the latest API)

3
  • How are you decoding the JSON into the object? Some methods decrypt a single level and others do the whole thing. Knowing the method you chose will help us answer your question. Commented Jul 25, 2019 at 16:31
  • 1. for Typescript, if you find the need to cast to any, you probably have a problem 2. examine the data in the debugger or with a console.log. It seems like the data is not in the place you think it is. Commented Jul 25, 2019 at 16:34
  • Thank you for your advice, I have updated it Commented Jul 25, 2019 at 16:34

1 Answer 1

4

You should create a type for your data. Because it's coming from an external source, typescript cannot infer that. Then parse your JSON and cast it to that type.

// Create a type for the expernal data.
interface Data {
    rates: {
        [currency: string]: number
    }
    base: string
    date: string
}

// Result of `JSON.parse()` will be `any`, since typescript can't parse it.
const untypedData = JSON.parse(`{
  "rates": {
    "CAD": 1.4591,
    "HKD": 8.6851,
    "ISK": 135.9,
    "PHP": 56.797,
    "DKK": 7.4648
  },
  "base": "EUR",
  "date": "2019-07-25"
}`)

// Cast the untyped JSON to the type you expect it to be.
const data: Data = untypedData

// Use the data according to it's type.
alert(data.rates.CAD)

Working demo on typescript playground

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.