0

I'm trying to make my code more efficient and reusable by adding variables on my requests and console.log. But for some reason its not working and I can't figure out why! full code can be found at: https://codesandbox.io/s/wispy-lake-6h051

This works:

  state = {
    lastWeek: '2020-11-09',
    today: '2020-11-12',
    selectedBase: 'USD',
    firstDateValues: null,
    fifthDateValues: null
  };

  getAPI = async() => {
    const START_DATE = this.state.lastWeek;
    const END_DATE = this.state.today;
    const BASE = this.state.selectedBase;
    
    const response = await fixer.get(`?start_at=${START_DATE}&end_at=${END_DATE}&base=${BASE}`, {
    });
    console.log(BASE) ---> output: USD
    console.log(response.data.rates[START_DATE].USD) --> correct data
}

But this doesn't:

  state = {
    lastWeek: '2020-11-09',
    today: '2020-11-12',
    selectedBase: 'USD',
    firstDateValues: null,
    fifthDateValues: null
  };

  getAPI = async() => {
    const START_DATE = this.state.lastWeek;
    const END_DATE = this.state.today;
    const BASE = this.state.selectedBase;
    
    const response = await fixer.get(`?start_at=${START_DATE}&end_at=${END_DATE}&base=${BASE}`, {
    });
    console.log(BASE) ---> output: USD
    console.log(response.data.rates[START_DATE].BASE) --> output: undefined 
}

Why?

Owen
  • 178
  • 2
  • 7
  • Does this answer your question? [Add a property to a JavaScript object using a variable as the name?](https://stackoverflow.com/questions/695050/add-a-property-to-a-javascript-object-using-a-variable-as-the-name) – Jared Smith Nov 13 '20 at 23:15

1 Answers1

3

What you need to do is to change

response.data.rates[START_DATE].BASE

to

esponse.data.rates[START_DATE][BASE]

because if you are using .BASE, it means BASE key, not your key from BASE variable

Artem Matiushenko
  • 814
  • 10
  • 14